gpt4 book ai didi

java - Apache POI,表定位被忽略(.docx、xwpf)

转载 作者:行者123 更新时间:2023-12-02 12:03:12 26 4
gpt4 key购买 nike

我尝试使用 tblPr 元素及其属性 tblpX 和 tblpY 来定位表格。我的问题是,当我打开 .docx 文件时,表格位于页面的左上角,忽略 tblpX 和 tblPY 值。您可以找到有关 .docx 表如何定位的详细信息 herehere 。它应该看起来像:

<w:tbl>
<w:tblPr>
<w:tblpPr w:vertAnchor="text" w:tblpY="200" />
</w:tblPr>

</w:tbl>

Apache POI 不提供“tblpY”和“tblpX”属性,因此我认为添加此属性的唯一方法是手动。这是我的代码:

public static XWPFTable createTable(XWPFDocument doc) {

//CTTbl ctTable = CTTbl.Factory.newInstance();
XWPFTable table = doc.createTable();//new XWPFTable(ctTable, doc, 0, 0);

XmlObject x = (XmlObject) table.getCTTbl().getTblPr();
XmlCursor c = x.newCursor(); // Create a cursor at the element
c.toNextToken(); // Move cursor after the tblPr tag
c.insertElement("tblPr", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");

c.toPrevSibling(); //Now go to the tblPr
XmlObject x2 = c.getObject(); //Get the tblPr object
c.dispose();
c = x2.newCursor(); //Now our cursor is inside the second tblPr
c.toNextToken();
c.insertAttributeWithValue("tblpX", "http://schemas.openxmlformats.org/wordprocessingml/2006/main", "500");
c.insertAttributeWithValue("tblpY", "http://schemas.openxmlformats.org/wordprocessingml/2006/main", "500");
c.dispose();

XWPFTableRow tr = table.getRow(0);
XWPFTableCell cell = tr.getCell(0);
cell.setText("some text");

return table;

}

我打开了 .docx 并验证了以下内容是否位于 document.xml 中

<w:tbl>
<w:tblPr>
<w:tblPr w:tblpX="500" w:tblpY="500"/>
<w:tblW w:w="0" w:type="auto"/>
<w:tblBorders>
<w:top w:val="single"/>
<w:left w:val="single"/>
<w:bottom w:val="single"/>
<w:right w:val="single"/>
<w:insideH w:val="single"/>
<w:insideV w:val="single"/>
</w:tblBorders>
</w:tblPr>
<w:tr>
<w:tc>
<w:p>
<w:r>
<w:t>some text</w:t>
</w:r>
</w:p>
</w:tc>
</w:tr>
</w:tbl>

那我做错了什么?为什么表格仍然在左上角?为什么 Microsoft Word 忽略我的 tblpX 和 tblpY 值?

最佳答案

tblPr 内的子节点应该是:tblpPr 不是 tblPr!

“p”语法上的单一差异让我感到困惑。

无论如何,希望有人能从中吸取教训。例如。 StackOverflow 还没有关于如何使用 Apache POI 绝对定位表格的解决方案...直到现在 mwahahaha

关于java - Apache POI,表定位被忽略(.docx、xwpf),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47098363/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com