export large list<> to excel C# MVC - c#

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.

Related

How to add dropdown list in gridview excel export

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();

Export gridview to excel WITHOUT gridview formatting

I have tried many things to just to export data only from the gridview. But it always export gridview formatting as well. Below is my code
private void ExportGridToExcel()
{
Response.Clear();
Response.Buffer = true;
Response.ClearContent();
Response.ClearHeaders();
Response.Charset = "";
string fileName = "QAFormNotReceived" + DateTime.Now.ToString("yyyy-MM-dd") + ".xls";
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
gvInsQANotReceived.HeaderStyle.Reset();
gvInsQANotReceived.FooterStyle.Reset();
gvInsQANotReceived.AlternatingRowStyle.Reset();
gvInsQANotReceived.RowStyle.Reset();
gvInsQANotReceived.BackColor = Color.Transparent;
gvInsQANotReceived.GridLines = GridLines.None;
gvInsQANotReceived.RenderControl(htmlTextWriter);
Response.Write(stringWriter.ToString());
Response.End();
}
This the Excel spreadsheet
Spreadsheet I require
Any help is appreciated. I know next option is to try to use a string builder and write the rows one by one.
Thanks

asp.net export to Excel UTF-8

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();

Excel export is not working with WebControl table

in my application i have bind sql data source to grid view, on click of export button i took gridviews datasource in datatable and created webControl table and write that control to xls file. but i am getting follwowing error:
Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.
My code is as follows:
HttpResponse Response = HttpContext.Current.Response;
Response.Clear();
string StudNm = Request["hidStudnm"];
Response.AddHeader("content-disposition", "attachment;filename=" + "StudentPasswordReport" + ".xls");
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
System.Web.UI.WebControls.Table tblRept;
tblRept = CreateTable(exportDt);
tblRept.RenderControl(htmlWrite);
please tell me why this error is occurred and how can i resole this error
You could try this
DataTableToExcel(exportDt);
private void DataTableToExcel(DataTable dataTable)
{
StringWriter writer = new StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(writer);
GridView gridView = new GridView();
gridView.DataSource = dataTable;
gridView.AutoGenerateColumns = true;
gridView.DataBind();
gridView.RenderControl(htmlWriter);
htmlWriter.Close();
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");
Response.Charset = "";
Response.Write(writer.ToString());
Response.End();
}

when exporting more then 500000 records in excel using C# .net it gives System.OutOfMemoryException was unhandled by user code

I stuck in the issue of exporting excel it gives error System.OutOfMemoryException in excel 2007 we cam export 1000000 rows but while exporting more then 250000 rows its gives the error the logic to upload the excel as i am using is
Response.Clear();
Response.Charset = "";
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
string FileName = "PoliciesDetailsForBranch";
Response.AppendHeader("content-disposition", "attachment; filename=" + FileName + ".xls");
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw);
GridView gv = new GridView();
this.EnableViewState = false;
gv.DataSource = (DataTable)dt;
gv.DataBind();
this.ClearControls(gv);
gv.RenderControl(hw);
Response.Write(sw.ToString());
Response.End();
Can any one give me the solution to cope up with this issue.
Instead of using a StringBuilder and causing the whole thing to be converted to a string in memory, send it directly to the Response.Output.
Response.Buffer = true;//left unmodified, but why were you buffering?
Response.ContentType = "application/vnd.ms-excel";
string FileName = "PoliciesDetailsForBranch";
Response.AppendHeader("content-disposition", "attachment; filename=" + FileName + ".xls");
GridView gv = new GridView();
this.EnableViewState = false;
gv.DataSource = (DataTable)dt;
gv.DataBind();
this.ClearControls(gv);
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(Response.Output);
gv.RenderControl(hw);
Response.End();

Categories

Resources