Java 如何使用ApachePOI将Excel文档中的区域转换为表?

Java 如何使用ApachePOI将Excel文档中的区域转换为表?,java,excel,apache-poi,xssf,Java,Excel,Apache Poi,Xssf,我已经编写了一个应用程序,它从数据库获取数据,并使用ApachePOI库中的XSSF类从所述数据创建Excel文档。我已经导入了poi、poi ooxml和poi ooxml模式,都是4.1.0版 文件写得很好,打开文件时没有错误,直到我取消注释表创建代码,我将在下面粘贴该代码: CellReference topLeft = new CellReference(sheet.getRow(3).getCell(0)); CellReference bottomRight = new CellRe

我已经编写了一个应用程序,它从数据库获取数据,并使用ApachePOI库中的XSSF类从所述数据创建Excel文档。我已经导入了poi、poi ooxml和poi ooxml模式,都是4.1.0版

文件写得很好,打开文件时没有错误,直到我取消注释表创建代码,我将在下面粘贴该代码:

CellReference topLeft = new CellReference(sheet.getRow(3).getCell(0));
CellReference bottomRight = new CellReference(sheet.getRow(nextRow-1).getCell(3));
AreaReference tableArea = workbook.getCreationHelper().createAreaReference(topLeft, bottomRight);
XSSFTable dataTable = sheet.createTable(tableArea);
我添加了几个附加字段,只是为了排除一些潜在问题:

int test = dataTable.getEndRowIndex(); //Returns 968, as expected
tableArea = dataTable.getArea(); //The area remains A4 to D968, as expected
int testColumns = dataTable.getColumnCount(); //Returns 4, as expected
int testRows = dataTable.getRowCount(); //Returns 968, as expected
在取消注释上述代码后尝试打开工作簿时,出现以下错误:

我们发现“filename.xlsx”中的某些内容有问题。是否希望我们尽可能多地尝试恢复?如果您信任此工作簿的来源,请单击“是”

单击“是”后,数据将在不显示表格的情况下显示,并显示以下错误: “已删除部分:/xl/tables/table1.xml包含xml错误的部分。(表)加载错误。第2行,第94列。”


这是令人困惑的,因为所有指示都表明表中应该只有4列。。。有人知道可能发生了什么以及如何修复吗?

您的
XSSFTable
缺少名称。至少必须使用设置显示名称

所以
dataTable.setDisplayName(“表1”)应该可以解决您的问题

如何检测

首先创建一个简单完整的示例。然后,在使用
Excel
打开结果后,注意错误是关于
/xl/tables/table1.xml
的哪一行/哪一列。然后在解压缩
*.xlsx
后打开
/xl/tables/table1.xml
。现在您应该发现,错误的
XML
是:

<table id="1" ref="A4:D..." xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><tableColumns count="4">

您的
XSSFTable
缺少名称。至少必须使用设置显示名称

所以
dataTable.setDisplayName(“表1”)应该可以解决您的问题

如何检测

首先创建一个简单完整的示例。然后,在使用
Excel
打开结果后,注意错误是关于
/xl/tables/table1.xml
的哪一行/哪一列。然后在解压缩
*.xlsx
后打开
/xl/tables/table1.xml
。现在您应该发现,错误的
XML
是:

<table id="1" ref="A4:D..." xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><tableColumns count="4">