首页 > 解决方案 > 如何将表格格式添加到 Excel 工作表中

问题描述

将数据写入工作表后,我正在尝试添加表格格式。我遇到了这个博客,它有 POI 而不是 NPOI 实现。所以我尝试在 C# 中编写更苗条的代码。

我试过的代码:

XSSFTable my_table = ((XSSFSheet)sheet).CreateTable();
CT_Table cttable = my_table.GetCTTable();
CT_TableStyleInfo table_style = new CT_TableStyleInfo();
cttable.tableStyleInfo = table_style;
table_style.name = "TableStyleMedium9";

table_style.showColumnStripes = false;
table_style.showRowStripes = true;
AreaReference my_data_range = new AreaReference(new CellReference(5, 0), new CellReference(10, 4));
cttable.@ref = my_data_range.FormatAsString();
cttable.displayName = "MYTABLE";
cttable.name = "Test";
cttable.id = 12;

注意: 找不到替代 CTTableStyleInfo table_style = cttable.addNewTableStyleInfo(); 功能addNewTableStyleInfo()不可用所以尝试像

CT_TableStyleInfo table_style = new CT_TableStyleInfo();
cttable.tableStyleInfo = table_style;

将流写入文件时:

(await workbook.ConfigureAwait(false)).Write(stream);

获得例外:

System.NullReferenceException:“对象引用未设置为对象的实例。”

堆栈跟踪:

   at NPOI.XSSF.UserModel.XSSFTable.UpdateHeaders()
   at NPOI.XSSF.UserModel.XSSFTable.WriteTo(Stream out1)
   at NPOI.XSSF.UserModel.XSSFTable.Commit()
   at NPOI.POIXMLDocumentPart.OnSave(List`1 alreadySaved)
   at NPOI.POIXMLDocumentPart.OnSave(List`1 alreadySaved)
   at NPOI.POIXMLDocumentPart.OnSave(List`1 alreadySaved)
   at NPOI.POIXMLDocument.Write(Stream stream)
   at App..Facade.MainFacade.<BuildReportAsync>d__25.MoveNext() in C:\App..\MainFacade.cs:line 215

如果我删除表格部分,那么工作正常,这意味着表格格式有问题。请帮忙。

标签: c#excelnpoixssf

解决方案


推荐阅读