我正在阅读两个docx文件,并将第一个表格单元格中的文本替换为第二个文本。要替换的细胞中有一个标记( [#indicator#] )。 该文本将写入表格的单元格中,其中标记确实存在。我的问题是在写入单元格后,单元格的开头总是有一些空白空间。高于" Rechnerische Ergebnisse:"在图片中。 如何在单元格的开头写入,或删除空白区域? 这是代码:
private void insertText(final XWPFDocument docxErsetzt) throws FileNotFoundException, IOException {
FileInputStream fis = new FileInputStream("src\\main\\resources\\WordTemplate\\text.docx");
XWPFDocument textInhalt = new XWPFDocument(fis);
List<XWPFParagraph> paragraphsInhat = textInhalt.getParagraphs();
List<XWPFTable> table = docxErsetzt.getTables();
for (XWPFTable xwpfTable : table) {
List<XWPFTableRow> row = xwpfTable.getRows();
for (XWPFTableRow xwpfTableRow : row) {
List<XWPFTableCell> cell = xwpfTableRow.getTableCells();
for (XWPFTableCell c : cell) {
if (c.getText().contains("[#indicator#]")) {
// remove [#indicator#]
c.removeParagraph(0);
for (XWPFParagraph para : paragraphsInhat) {
XWPFRun newRun = c.addParagraph().createRun();
newRun.removeBreak();
newRun.removeCarriageReturn();
newRun.setText(para.getText(), 0);
for (XWPFRun run : para.getRuns()) {
String textInRun = run.getText(0);
if (textInRun == null || textInRun.isEmpty()) {
continue;
}
newRun.setFontSize(run.getFontSize());
newRun.setFontFamily(run.getFontFamily());
newRun.setBold(run.isBold());
newRun.setItalic(run.isItalic());
newRun.setStrikeThrough(run.isStrikeThrough());
newRun.setUnderline(run.getUnderline());
newRun.setColor(run.getColor());
}
}
}
}
}
}
docxErsetzt.write(new FileOutputStream(OUTPUTPATH + "textreplaced.docx"));
docxErsetzt.close();
textInhalt.close();
}
答案 0 :(得分:2)
XWPFParagraph
由一个或多个XWPFRun
个实例组成,请勿删除该段落,尝试以这种方式更改其内容:
public void changeText(XWPFParagraph p, String newText) {
List<XWPFRun> runs = p.getRuns();
for(int i = runs.size() - 1; i > 0; i--) {
p.removeRun(i);
}
XWPFRun run = runs.get(0);
run.setText(newText, 0);
}