我想使用 EPPlus 将数据表导出到 Excel 文件。该数据表具有 int 类型的属性,因此我希望 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.
错误。这是我的代码
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();
}
这是将数据集导出到 Excel 的片段:
private static void DataSetToExcel(DataSet dataSet, string filePath)
{
using (ExcelPackage pck = new ExcelPackage())
{
foreach (DataTable dataTable in dataSet.Tables)
{
ExcelWorksheet workSheet = pck.Workbook.Worksheets.Add(dataTable.TableName);
workSheet.Cells["A1"].LoadFromDataTable(dataTable, true);
}
pck.SaveAs(new FileInfo(filePath));
}
}
并使用语句:
using OfficeOpenXml;
using System.Data;
using System.IO;
ExcelPackage.LicenseContext = LicenseContext.NonCommercial
如果您在商业上使用它,您的公司可以获得许可证或使用 v4.5.3.3(它在 netcore/net5 中工作),这是最后一个可以在商业上免费使用的版本
以下代码适用于 4.5.3.3
DataTable 到 Excel,使用列名作为 Excel 标题。
之后它还会遍历表格并设置任何 DateTime 列,以便它们在 Excel 中显示为日期,而不是像 45123 这样的数字
DataTable dt = ...;
string sheetName = ...;
string dateFormat = "yyyy-MM-dd HH:mm:ss";
using var p = new ExcelPackage();
var ws = p.Workbook.Worksheets.Add(sheetName);
ws.Cells["A1"].LoadFromDataTable(dt, PrintHeaders: true);
for (int c = 0; c < dt.Columns.Count; c++)
{
if (dt.Columns[c].DataType == typeof(DateTime))
{
ws.Column(c + 1).Style.Numberformat.Format = dateFormat;
}
}
如果您在例如 API 控制器中使用它,您可以使用以下命令将其作为下载文件返回:
string fileName = ...; //without extension
return File(p.GetAsByteArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName + ".xlsx");
注意范围using
!它是 C#8 语法,直到它声明的块结束
与上面相同,但在 VB 中:
Dim dt As DataTable = ...
Dim sheetName As String = ...
Dim dateFormat As String = "yyyy-MM-dd HH:mm:ss"
Using p As New ExcelPackage()
Dim ws = p.Workbook.Worksheets.Add(sheetName)
ws.Cells("A1").LoadFromDataTable(dt, PrintHeaders:=True)
For c As Integer = 0 To dt.Columns.Count - 1
If dt.Columns(c).DataType Is GetType(Date) Then
ws.Column(c + 1).Style.Numberformat.Format = dateFormat
End If
Next
End Using
并且对于下载,它必须放在 using 块内
Dim fileName As String = ... 'without extension
Return File(p.GetAsByteArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName & ".xlsx")