我有.docx,其内容为表格。在此表内部,我检查每个单元格是否包含(实例)XWPFParagraph或XWPFTable。然后,执行条件,如果一个单元格包含XWPFParagraph,那么我会做某事(在这种情况下,我查找并替换文本),如果一个单元格包含XWPFTable,那么我将复制表并将其放在现有表之后。
所以,我有这段代码。
public class JavaApplication1 {
public static void main(String[] args) {
try {
FileInputStream filename = new FileInputStream("D:\\document300718\\NetBeansProjects\\JavaApplication1\\src\\docx\\template.docx");
XWPFDocument doc = new XWPFDocument(filename);
for (XWPFTable tbl : doc.getTables()) {
for (XWPFTableRow row : tbl.getRows()) {
for(int c = 0; c < row.getTableCells().size(); c++){
XWPFTableCell cell = row.getTableCells().get(c);
for(int p =0; p < cell.getBodyElements().size(); p++){
IBodyElement cellElem = cell.getBodyElements().get(p);
//Check if cell contains XWPFParagraph or XWPFTable
if(cellElem instanceof XWPFParagraph){
List<XWPFParagraph> paragraphs = cell.getParagraphs();
for(XWPFParagraph par : paragraphs){
List<XWPFRun> runs = par.getRuns();
String find = "EMPLOYEE_NM";
TextSegement found = par.searchText(find, new PositionInParagraph());
if(found!=null){
XWPFRun run = runs.get(found.getBeginRun());
String runText = run.getText(run.getTextPosition());
String replace = runText.replace(find, "Bruce");
run.setText(replace, 0);
}
}
}
else if (cellElem instanceof XWPFTable)
{
XWPFTable tabel = (XWPFTable) cellElem;
CTTbl ctTabel = tabel.getCTTbl();
XmlCursor tblCursor = ctTabel.newCursor();
tblCursor.toEndToken();// to put cursor after table
while(tblCursor.toNextToken() != org.apache.xmlbeans.XmlCursor.TokenType.START);
//Main Problem
XWPFTable newTable = cell.insertNewTbl(tblCursor);//causing infinite loop
CTTbl ctTbl = newTable.getCTTbl();
CTTbl copyCT = CTTbl.Factory.newInstance();
copyCT.set(tabel.getCTTbl());
ctTbl.set(copyCT);
}
}
}
}
}
}
doc.write(new FileOutputStream("D:\\document300718\\NetBeansProjects\\JavaApplication1\\src\\docx\\template1.docx"));
} catch (Exception e) {
e.printStackTrace();
}
}}
放置时出现无限循环(甚至Java堆空间)
XWPFTable newTable = cell.insertNewTbl(tblCursor);
但是,如果我插入新段落以使用XWPFParagraph para = cell.insertNewParagraph(tblCursor);
在表格后放置文字,则效果很好。
那么,关于如何解决此问题的任何建议?
注意: 我有参考 这些链接中的to put cursor after table和copy table。