I have found lots of examples and tutorials about how to export a DataTable
as Excel by using epplus, but I cannot find a direct way to do it. Therefore I tried the following code..
my dataTable:
===============================
d1 | d2 | d3
===============================
aa1 | bb1 | cc1
aa2 | bb2 | cc2
aa3 | bb3 | cc3
aa4 | bb4 | cc4
script:
using OfficeOpenXml;
using OfficeOpenXml.Drawing;
//........
protected viod exportToExcel (dataTable dt)
{
try
{
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=" + HttpUtility.UrlEncode("Logs.xlsx", System.Text.Encoding.UTF8));
using (ExcelPackage pck = new ExcelPackage())
{
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Logs");
ws.Cells["A1"].LoadFromDataTable(dt, true);
var ms = new System.IO.MemoryStream();
pck.SaveAs(ms);
ms.WriteTo(Response.OutputStream);
}
}
catch (Exception ex)
{
Debug("error: " + ex.Message);//catch nothing
}
}
It returns a server error and no any exception is caught, so I have no idea what error happens..
However, no error occurs when I remove the
using (ExcelPackage pck = new ExcelPackage())
section in above code.
Any ideas?
Best way to export to excel from server, convert the data table to HtmlTextWriter. In the Response.AddHeader("content-disposition","attachment;filename=file.xls");
Response.ContentType="application/vnd.ms-excel"; and finally
Response.Output.Write(htmltexwriter)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.