gpt4 book ai didi

java - 使用apache poi将表格插入到word文档的特定位置

转载 作者:行者123 更新时间:2023-12-01 07:54:34 25 4
gpt4 key购买 nike

我正在开发一个项目,尝试创建一个自动报告生成器。我需要找出几个特定的​​段落,删除已有的表格并插入一个新表格。

到目前为止一切都很完美。我什至设法在我想要的位置插入示例文本,但是...无论我做什么,所有表格都放置在文档的末尾。

public class InsertText {
public static void main(String[] args) throws FileNotFoundException, IOException,
InvalidFormatException {
try {
FileInputStream fis = new FileInputStream("c:\\Work\\current\\***.docx");
XWPFDocument document = new XWPFDocument(OPCPackage.open(fis));
fis.close();
System.out.println(document.getDocument().getBody().getPArray().length);
List<IBodyElement> elements = document.getBodyElements();
for (int n = 0; n < elements.size(); n++) {
IBodyElement element = elements.get(n);
if (element instanceof XWPFParagraph) {
XWPFParagraph p1 = (XWPFParagraph) element;
List<XWPFRun> runList = p1.getRuns();
StringBuilder sb = new StringBuilder();
for (XWPFRun run : runList)
sb.append(run.getText(0));
if (sb.toString().contains("????")) {
n++;
element = elements.get(n);
if (element instanceof XWPFTable) {
XWPFTable t = (XWPFTable) element;
XmlCursor cursor = t.getCTTbl().newCursor();
document.removeBodyElement(n);
XWPFParagraph p = document.insertNewParagraph(cursor);
XWPFRun run = p.createRun();
run.setText("GOAL!!!");
XWPFTable t2 = document.createTable(3,4);
XWPFTableCell cell = t2.getRow(0).getCell(0);
document.insertTable(n, t2);
cell.setText("GOAL!!!");
t2 = p.getBody().insertNewTbl(cursor);
}
}
}
}
FileOutputStream outStream = new FileOutputStream("C:/Work/Current/**.docx");
document.write(outStream);
outStream.close();
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
}

最佳答案

//first row
XWPFTableRow rowOfOriginalTable = theOriginalTable.getRow(0);

//second cell of the first row
XWPFTableCell cellOfOriginalTable = rowOfOriginalTable.getCell(1);

//new paragraph in that cell
XWPFParagraph p = cellOfOriginalTable.addParagraph();

//get the cursor of the new paragraph
XmlCursor cursor = p.getCTP().newCursor();

//add the nested Table
XWPFTable nestedTable = p.getBody().insertNewTbl(cursor);

//add the first row to the nested table
XWPFTableRow rowOfNestedTable = nestedTable.createRow();

//add a cell to the first row
XWPFTableCell cellOfNestedTable = rowOfNestedTable.createCell();

//add a value
cellOfNestedTable.setText("Cell 0,0");

//add another cell
cellOfNestedTable = rowOfNestedTable.createCell();
cellOfNestedTable.setText("Cell 0,1");


//add another cell and rows
rowOfNestedTable = nestedTable.createRow();
cellOfNestedTable = rowOfNestedTable.getCell(0);
cellOfNestedTable.setText("Cell 1,0");

cellOfNestedTable = rowOfNestedTable.getCell(1);
cellOfNestedTable.setText("Cell 1,1");

cellOfOriginalTable.addParagraph();

关于java - 使用apache poi将表格插入到word文档的特定位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31835579/

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