using NPOI.XSSF.UserModel;
var workbook = new XSSFWorkbook();
var sheet = (XSSFSheet)workbook.CreateSheet("Sheet1");
// 在 sheet里面创建一个表
var table = sheet.CreateTable();
table.Name = "Test";
var ctTable = table.GetCTTable();
ctTable.id = 1;
table.IsHasTotalsRow = false;
table.DisplayName = "Table1";
table.SetCellReferences(new NPOI.SS.Util.AreaReference("A1:C5", NPOI.SS.SpreadsheetVersion.EXCEL2007));
// 创建三个 cloumn
table.CreateColumn(null, 0);
table.CreateColumn(null, 1);
table.CreateColumn(null, 2);
table.StyleName = XSSFBuiltinTableStyleEnum.TableStyleMedium27.ToString();
table.Style.IsShowColumnStripes = false;
table.Style.IsShowRowStripes = true;
// 填充数据
for (int r = 0; r < 5; r++)
{
var row = sheet.CreateRow(r);
for (int c = 0; c < 3; c++)
{
var cell = row.CreateCell(c);
if (r == 0)
{
// 第一行是 列名
cell.SetCellValue("Column" + (c + 1));
}
else
{
// 数据
cell.SetCellValue($"R{r + 1}C{c + 1}");
}
}
}
// 把 workbook 写入到文件流
using (FileStream sw = File.Create("test.xlsx"))
{
workbook.Write(sw);
}
会生成如下格式的 excel
Column1 Column2 Column3
R2C1 R2C2 R2C3
R3C1 R3C2 R3C3
R4C1 R4C2 R4C3
R5C1 R5C2 R5C3