C# NPOI Export DataTable C# NPOI导出DataTable 单元格自适应大小
1.Install-Package NPOI -v 2.4.0
2.
using NPOI.XSSF; using NPOI.XSSF.UserModel; using NPOI.SS.UserModel; using System.IO; static void ExportDataTable(DataTable dt) { string exportedExcelFullName = Directory.GetCurrentDirectory() + "//" + DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".xlsx"; if(dt!=null && dt.Rows.Count>0) { XSSFWorkbook workBook = new XSSFWorkbook(); ISheet firstSheet = workBook.CreateSheet("First Sheet"); IRow headerRow = firstSheet.CreateRow(0); for(int i=0;i<dt.Columns.Count;i++) { ICell headerCell = headerRow.CreateCell(i); headerCell.SetCellValue(dt.Columns[i].ColumnName?.ToString()); } for (int i = 0; i < dt.Rows.Count; i++) { IRow dataRow = firstSheet.CreateRow(i + 1); for(int j=0;j<dt.Columns.Count;j++) { ICell dataCell = dataRow.CreateCell(j); dataCell.SetCellValue(dt.Rows[i][j]?.ToString()); } } for(int i=0;i<dt.Columns.Count;i++) { firstSheet.AutoSizeColumn(i); } using (FileStream excelStream = File.Create(exportedExcelFullName)) { workBook.Write(excelStream); } } }
3.让Excel单元格自适应单元格大小
for(int i=0;i<dt.Columns.Count;i++)
{
firstSheet.AutoSizeColumn(i);
}
最后效果: