Here is my code :
var model = _db.FacebookInfo.OrderByDescending(f => f.Followers).ToList();
var grid = new System.Web.UI.WebControls.GridView();
grid.DataSource = (from u in model
select new
{
fullname = System.Text.RegularExpressions.Regex.Replace(u.FullName, "<span .*?>(.*?)", ""),
followers = u.Followers,
friends = u.Friends,
url = u.FbLink
}).ToList();
grid.DataBind();
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=Nana bregvadze Friends.xls");
Response.ContentType = "application/excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
grid.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
It just create an excel file, but i have an unicode problem, can't read Georgian charachters. Look at the picture :
Maybe it's a duplicate but no solution worked for me.
Your code doesn't create a real XLSX file, it creates an HTML table with a faked header and extension. Excel will import this file using the end user's default settings and locale.
Instead of faking Excel files, you can easily create a real XLSX file with minimal code using a library like EPPlus. There's even a Web Application example in the Codeplex site. You can use LoadFromCollection instead of LoadFromDataTable in your case:
using (ExcelPackage pck = new ExcelPackage())
{
//Create the worksheet
var ws = pck.Workbook.Worksheets.Add("Demo");
//Load the datatable into the sheet, starting from cell A1.
// Print the column names on row 1
var table=ws.Cells["A1"].LoadFromCollection(model, true);
//Write it back to the client
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=ExcelDemo.xlsx");
Response.BinaryWrite(pck.GetAsByteArray());
}
Note that table is an actual ExcelRange object, that can be given a name, style etc.
Okey i solve the problem :
just change Response.ClearContent() to Response.Clear() and add
Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />")
full code :
var model = _db.FacebookInfo.OrderByDescending(f => f.Followers).ToList();
var grid = new System.Web.UI.WebControls.GridView();
grid.DataSource = (from u in model
select new
{
fullname = System.Text.RegularExpressions.Regex.Replace(u.FullName, "<span .*?>(.*?)", ""),
followers = u.Followers,
friends = u.Friends,
url = u.FbLink
}).ToList();
grid.DataBind();
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=Nana bregvadze Friends.xls");
Response.ContentType = "application/excel";
Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
grid.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
Related
Currently my method is use for export excel file from gridview. Now I want to create dropdown list in some column for each row of excel file. It's possible to do with StringWriter?
There is my code of the method...
string exportFileName = Session["corpUser"].ToString() + "_ProjectExport_" + unixTimestamp + ".xls";
//Create a dummy GridView
GridView dummyGridView = new GridView();
dummyGridView.AllowPaging = false;
dummyGridView.DataSource = dt;
dummyGridView.DataBind();
//Write Dummy Gridview to Excel File
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=" + exportFileName);
Response.ContentType = "application/ms-excel";
Response.ContentEncoding = System.Text.Encoding.Unicode;
Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(sw);
dummyGridView.RenderControl(hw);
Response.Write(sw.ToString());
Response.End();
I want to export a list with over 10000 rows to excel using MVC5 C#.
when I export using DataGrid some columns are not shown in the excel file - 3 columns are disapeard in the excel file but all the 10000 rows appeard.
string filename = Guid.NewGuid() + ".xls";
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
DataGrid dgGrid = new DataGrid();
List registrationsetList = db.RegistrationSet.Where(x => x.QuestionId == TheQuestion.Id).ToList();
dgGrid.DataSource = registrationsetList;
dgGrid.DataBind();
dgGrid.RenderControl(hw);
Response.BinaryWrite(System.Text.Encoding.UTF8.GetPreamble());
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
Response.Write(tw.ToString());
Response.End();
If I change DataGrid dgGrid = new DataGrid()
to GridView dgGrid = new GridView();
with list of 600 of rows, the excel looks perfect with all the columns.
the problem is when i export all the list of 10000 rows, the excel file got stuck - i got not responding message.
why ?
Instead of using a DataGrid() try using a WebControl GridView():
string filename = Guid.NewGuid() + ".xls";
var gv = new System.Web.UI.WebControls.GridView();
var registrationsetList = db.RegistrationSet.Where(x => x.QuestionId == TheQuestion.Id);
g.DataSource = registrationsetList;
gv.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=" + filename);
Response.ContentType = "application/ms-excel";
Response.Charset = "";
StringWiter sw = new StringWriter();
var htw = new System.Web.UI.HtmlTextWriter(sw);
gv.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
The problem (with that stucked excel file) was solved with DataGrid. The problem was that the DateGrid doen't show columns of nullable fields in the CLASS in the list that i bound to the GridView.
I am dumping the data from a table to an excel sheet which is created during run time.I have the file path in Session["Fullpath"]. I am able to create the excel with contains the data of table1.Now, I have one more table table2.I want to dump the data from table table2 to the second sheet of the same excel.
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename= " + Session["Fullpath"]);
Response.ContentType = "application/ms-excel";
Response.Charset = "";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
table.RenderControl(htw);
Response.Output.Write(sw.ToString());
System.IO.File.WriteAllText(Session["Fullpath"].ToString(), sw.ToString());
Response.Flush();
Response.End();
I generate Excel document in ASP.Net with below code:
if (dataTable.Rows.Count > 0)
{
var tw = new StringWriter();
var hw = new System.Web.UI.HtmlTextWriter(tw);
var dgGrid = new DataGrid();
dgGrid.DataSource = dataTable;
dgGrid.DataBind();
dgGrid.RenderControl(hw);
attachment = "attachment; filename=" + fileName + ".xls";
Response.Charset = "UTF-8";
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("content-disposition", attachment);
outputResponse = tw.ToString();
}
But when I want to open Excel document it gives error:
Error: excel cannot open the file .xls because the file format or
file extension is not valid
How can I solve it?
Either use a reference to the Excel Application object to create an actual excel file, use one of the many codeplex based projects to create an Excel spreadsheet or most easily create a CSV file from your datagrid and return that, which many users computers will prompt them to open in Excel.
Just tried your code, with exception of the last line, which I've changed:
var tw = new StringWriter();
var hw = new System.Web.UI.HtmlTextWriter(tw);
var dgGrid = new DataGrid();
dgGrid.DataSource = dataTable;
dgGrid.DataBind();
dgGrid.RenderControl(hw);
var attachment = "attachment; filename=" + fileName + ".xls";
Response.Charset = "UTF-8";
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("content-disposition", attachment);
// outputResponse = tw.ToString();
Response.Output.Write(tw.ToString());
Response.Flush();
Response.End();
My datatable is a 2-col table with simple data (letters and numbers)and it is opened as it should.
You will get the message that says:
The file you are trying to open'yourfilename.xls', is in a different
format thahn specified by the file extension. Verify that the file is
not corrupted and is from a trusted source before opening the file. Do
you want to open the file now?
After clicking OK the file opens just fine.
I have a code that will generate an excel report.i am using ASP.NET MVC 4. I googled and found the same code everywhere still my code is not working why. My code in controller is as:
public ActionResult ExportData()
{
string[] abc = { "AAA", "BBB", "CCC" };
GridView gv = new GridView();
gv.DataSource = abc;
gv.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=Marklist.xls");
Response.ContentType = "application/ms-excel";
Response.Charset = "";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
return RedirectToAction("_EligibilityCriteria");
}
Just to test the export functionality I used an array abc this code is working in .net application but not in ASP.NET MVC 4 application. I have debugged the code but not found a problem or error in code.
What am I doing wrong here?
Finally found a way to export to excel.
public void ExportIniEmployeeToExcel(EligibilityCriteriaModel AllIniEmp)
{
List<AllIniEmployees> emp = new List<AllIniEmployees>();
AllIniEmp.allSuccessEmployeeList.ForEach(x =>
{
AllIniEmployees allEmp = new AllIniEmployees();
allEmp.EmployeeCode = x.EmployeeCode;
allEmp.EmployeeName = x.EmployeeName;
allEmp.Designation = x.Designation;
allEmp.DeliveryTeam = x.DeliveryTeam;
allEmp.ConfirmationDate = x.ConfirmationDate;
emp.Add(allEmp);
});
GridView gv = new GridView();
gv.DataSource = emp;
gv.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=InitiatedEmployees.xls");
Response.ContentType = "application/ms-excel";
Response.Charset = "";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
here i used parent class as a parameter and used linq.now its working perfectly fine.
thank you all.
You can't just write the output with a StringWriter. After your call to RenderControl, write:
byte[] byteArray = Encoding.ASCII.GetBytes(sw.ToString());
MemoryStream s = new MemoryStream(byteArray);
StreamReader sr = new StreamReader(s, Encoding.ASCII);
Response.Write(sr.ReadToEnd());
Response.End();
Try returning a ContentResult instead of writing directly to the output stream.