Adding Multiple worksheet with excel while export in mvc - c#

Actually i am looking to export an excel file from dataTable. I managed to do it. But how can i add an empty sheet in the same excel file while exporting from dataTable?
Here is my code :
public void ExportToExcel(DataTable dts)
{
if (dts.Rows.Count > 0)
{
string filename = "2.Dependent Master.xls";
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
DataGrid dgGrid = new DataGrid();
dgGrid.DataSource = dts;
dgGrid.DataBind();
dgGrid.RenderControl(hw);
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
Response.Write(tw.ToString());
Response.End();
}
}
Any help appreciated. Thanks in Advance !!!!

You can't add multiple worksheets with simple HTML.
instead of you can use Closed XML open source library
https://closedxml.codeplex.com/
Sample
var workbook = new XLWorkbook();
var worksheet1 = workbook.Worksheets.Add(PassYourDatatable1);
var worksheet2 = workbook.Worksheets.Add(PassYourDatatable2);
How to add Datatable to worksheet

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

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

export large list<> to excel C# MVC

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.

Export Datatable To Excel Format / Extension Error

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.

warning message while opening the excel file after export from gridview

i have written code to export data but warning message i am facing while opening the excel file and by default file is saving as .html extension
warning - "The file you are opening in a different format than specified by the file extension"
i need with .xls extension to be saved
please help me
private void ExportToExcel(DataTable dt)
{
string fileName = "FileName" + DateTime.Now.ToString("MMddyyyy_HHmmss") + ".xls";
Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
//Response.AddHeader("content-disposition", "attachment;filename=Filename .xls");
Response.ContentType = "application/vnd.ms-excel";
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWriter);
DataGrid dataExportExcel = new DataGrid();
dataExportExcel.ItemDataBound += new DataGridItemEventHandler(dataExportExcel_ItemDataBound);
dataExportExcel.DataSource = dt;
dataExportExcel.DataBind();
dataExportExcel.RenderControl(htmlWrite);
System.Text.StringBuilder sbResponseString = new System.Text.StringBuilder();
sbResponseString.Append("<html xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:x=\"urn:schemas-microsoft-com:office:xlExcel8\" xmlns=\"http://www.w3.org/TR/REC-html40\"> <head></head> <body>");
sbResponseString.Append(stringWriter + "</body></html>");
Response.Write(sbResponseString.ToString());
Response.End();
}
Use this one - http://www.gemboxsoftware.com/spreadsheet/overview
Looks like this in use:
// Create new Excel file.
var excelFile = new ExcelFile();
excelFile.Worksheets.Add(dt.TableName).InsertDataTable(dt, 0, 0, true);
// Save Excel file to XLS format.
excelFile.SaveXls(dataSet.DataSetName + ".xls");

Categories

Resources