Reputation: 829
I am reading a two docx files and replace text in table cell of the first one with the text from the second one. The cells which are to be replaced have a marker in them ([#indicator#]).
The text will be written in the cell of tables, in which the marker does exist. My problem is that there is always some empty space at the beginning of the cell after writing in it. Above the word "Rechnerische Ergebnisse:" in the picture.
How can I write at the beginning of the cell, or remove the empty space?
Here is the code:
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();
}
Upvotes: 0
Views: 163
Reputation: 4158
A XWPFParagraph
is made up of one or more XWPFRun
instances,don't remove the paragraph, try to change its content this way :
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);
}
Upvotes: 2