WeihanLi.Npoi
多 sheet 导出最近有位朋友在 Github 上提 issue 问,不同的集合类型怎么导出到同一个 excel 不同的 sheet 中,于是就想写篇文章分享一下,希望对需要的朋友有所帮助
废话不多说直接上代码吧,首先要导出到不同的 sheet 中需要自己准备一个 workbook 对象,再通过 ImportData
来导入数据
var collection1 = new[]
{
new TestEntity1() { Id = 1, Title = "test1" },
new TestEntity1() { Id = 2, Title = "test2" }
};
var collection2 = new[]
{
new TestEntity2() { Id = 1, Title = "test1", Description = "description"},
new TestEntity2() { Id = 2, Title = "test2" }
};
// 准备一个 workbook
var workbook = ExcelHelper.PrepareWorkbook(ExcelFormat.Xlsx);
// 导入 collection1 到第一个 sheet
workbook.ImportData(collection1);
// 导入 collection2 到第二个 sheet
workbook.ImportData(collection2, 1);
// 导出 workbook 到本地文件
workbook.WriteToFile("multi-sheets.xlsx");
最后通过 WriteToFile
去写入到文件或者自己将 workbook 导出到一个 stream 中。
如果需要自定义一些配置还是和之前是一样的,可以使用 attribute 的方式也可以使用 fluent API 的方式,如下:
[Sheet(SheetName = "TestSheet", SheetIndex = 0)]
file sealed class TestEntity1
{
[Column("ID", Index = 0)]
public int Id { get; set; }
public string Title { get; set; } = string.Empty;
}
file sealed class TestEntity2
{
public int Id { get; set; }
public string Title { get; set; } = string.Empty;
public string Description { get; set; }
}
Fluent API 配置如下:
var settings = FluentSettings.For<TestEntity2>();
settings.HasSheetSetting(sheet => sheet.SheetName = "TestEntity2", 1);
settings.Property(x => x.Id)
.HasColumnIndex(0)
.HasColumnOutputFormatter(v => v.ToString("#0000"))
;
settings.Property(x => x.Title)
.HasColumnIndex(1)
;
settings.Property(x => x.Description)
.HasColumnIndex(2)
;
导出结果如下:
sheet0
sheet1