1、nuget引入eppuls
2、将需要导出的数据存入DataTable
public void ExportExcel(string filePath,DataTable dt)
{
ExcelPackage.LicenseContext = LicenseContext.Commercial;
using (ExcelPackage excelPackage = new ExcelPackage(new FileInfo(filePath)))
{
ExcelWorkbook excelWorkbook = excelPackage.Workbook;
ExcelWorksheet dataSheet = excelWorkbook.Worksheets["数据页1"] ?? excelWorkbook.Worksheets.Add("数据页1");
ExportDataTableToExcelSheet(dataSheet, dt);
}
}
public void ExportDataTableToExcelSheet(ExcelWorksheet worksheet, DataTable dataTable,int startRow = 0)
{
int rowIndex = 1;
int columnIndex = 1;
foreach (DataColumn column in dataTable.Columns)
{
worksheet.Cells[rowIndex, columnIndex].Value = column.ColumnName;
worksheet.Cells[rowIndex, columnIndex].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
worksheet.Cells[rowIndex, columnIndex].Style.Fill.PatternType = ExcelFillStyle.Solid;
worksheet.Cells[rowIndex, columnIndex].Style.Fill.BackgroundColor.SetColor(Color.Green);
worksheet.Cells[rowIndex, columnIndex].Style.Font.Color.SetColor(Color.White);
columnIndex++;
}
rowIndex++;
for (int i = startRow; i < startRow + 65500; i++)
{
if (dataTable.Rows.Count - 1 < i)
{
break;
}
DataRow row = dataTable.Rows[i];
columnIndex = 1;
foreach (DataColumn column in dataTable.Columns)
{
worksheet.Cells[rowIndex, columnIndex].Value = row[column.ColumnName];
if (column.DataType == typeof(string) || column.DataType == typeof(String))
{
worksheet.Cells[rowIndex, columnIndex].Value = $"{row[column.ColumnName]}";
}
columnIndex++;
}
rowIndex++;
}
worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns();
}