C# 导出DataTable到Excel

 1 /// <summary>
 2 /// 将DataTable数据,存储到一个Excel中(.xlsx)
 3 /// </summary>
 4 /// <param name="dt"></param>
 5 /// <param name="filePath"></param>
 6 public static void ExportExcel(DataTable dt, string filePath)
 7 {
 8     // 创建工作表
 9     XSSFWorkbook workbook = new XSSFWorkbook();
10     var sheet = workbook.CreateSheet(dt.TableName);
11     // 单元格样式
12     ICellStyle style = workbook.CreateCellStyle();
13     style.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
14     style.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
15     style.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
16     style.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
17     // 创建标题行
18     var rowTilte = sheet.CreateRow(0);
19     // 创建标题行单元格名称
20     for (int c = 0; c < dt.Columns.Count; c++)
21     {
22         var cellid = rowTilte.CreateCell(c);
23         cellid.SetCellValue(dt.Columns[c].ColumnName);
24         rowTilte.Cells[c].CellStyle = style;
25     }
26     // 写数据
27     for (int i = 0; i < dt.Rows.Count; i++)
28     {
29         var rowData = sheet.CreateRow(i + 1);
30         for (int c = 0; c < dt.Columns.Count; c++)
31         {
32             var cellid = rowData.CreateCell(c);
33             cellid.SetCellValue(dt.Rows[i][c].ToString());
34             rowData.Cells[c].CellStyle = style;
35         }
36     }
37     // 列宽自动
38     for (int c = 0; c < dt.Columns.Count; c++)
39     {
40         sheet.AutoSizeColumn(c);
41     }
42     // 写文件
43     FileStream file = new FileStream(filePath, FileMode.CreateNew, FileAccess.Write);
44     workbook.Write(file);
45     file.Dispose();
46 }

依赖

NPOI.SS.UserModel
NPOI.XSSF.UserModel

 备注:如果要导出DataSet,只需要遍历DataSet的DataTable新建sheet即可。

posted @ 2022-10-10 11:51  Mr_Xul  阅读(81)  评论(0)    收藏  举报