导出DataTable以优于EPPlus

我想导出数据表到excel文件与EPPlus的数据表具有inttypes的属性,所以我想在Excel文件中,将相同的格式。 有没有人知道一种方法来导出一个DataTable到Excel与这些?

using (ExcelPackage pck = new ExcelPackage(newFile)) { ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Accounts"); ws.Cells["A1"].LoadFromDataTable(dataTable, true); pck.Save(); } 

这应该为你做的伎俩。 如果您的字段被定义为int EPPlus将正确地将列转换为数字或浮点数。

如果你想在浏览器响应下载

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

为了在浏览器中下载excelsheet,使用HttpContext.Current.Response而不是Response否则你将得到Response is not available in this context. error.Here是我的代码

 public void ExporttoExcel(DataTable table, string filename) { HttpContext.Current.Response.Clear(); HttpContext.Current.Response.ClearContent(); HttpContext.Current.Response.ClearHeaders(); HttpContext.Current.Response.Buffer = true; HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8; HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache); HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=GridData.xlsx"); using (ExcelPackage pack = new ExcelPackage()) { ExcelWorksheet ws = pack.Workbook.Worksheets.Add(filename); ws.Cells["A1"].LoadFromDataTable(table, true); var ms = new System.IO.MemoryStream(); pack.SaveAs(ms); ms.WriteTo(HttpContext.Current.Response.OutputStream); } HttpContext.Current.Response.Flush(); HttpContext.Current.Response.End(); }