在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
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++) 最后效果: |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论