Reputation: 31
I'm using Apache POI in order to create a docx containing a table.
In order to format the table, I'm adding paragraphs to the cell, using this method:
private XWPFParagraph getTableParagraph(XWPFDocument document, XWPFParagraph paragraph, String text, boolean bold, boolean wrap, boolean allineaDx){
if (paragraph == null) paragraph = document.createParagraph();
XWPFRun p2run = paragraph.createRun();
p2run.setText(text);
p2run.setFontSize(5);
p2run.setBold(bold);
if (wrap) paragraph.setWordWrap(wrap);
if (allineaDx) paragraph.setAlignment(ParagraphAlignment.RIGHT);
return paragraph;
}
and I call the method with:
XWPFTableRow tableOneRowOne = tableOne.getRow(0);
tableOneRowOne.getCell(0).setParagraph(getTableParagraph(document, tableOneRowOne.getCell(0).getParagraphArray(0), "some text", true, true, false));
the table comes out as desired, but all the paragraphs created and inserted in the cells are also visible at the end of the table. Why? How can I prevent this?
Upvotes: 1
Views: 2785
Reputation: 31
problem solved
the duplication was caused by document.createParagraph().
i changed the method into this:
private XWPFParagraph getTableParagraph(XWPFTableCell cell, String text, boolean bold, boolean wrap, boolean allineaDx) throws Exception{
XWPFParagraph paragraph = cell.addParagraph();
cell.removeParagraph(0);
XWPFRun p2run = paragraph.createRun();
p2run.setText(text);
p2run.setFontSize(5);
p2run.setBold(bold);
if (wrap) paragraph.setWordWrap(wrap);
if (allineaDx) paragraph.setAlignment(ParagraphAlignment.RIGHT);
return paragraph;
}
and now everything works just fine. Please note the cell.removeParagraph(0)
Cells come with a null paragraph on their own, and adding a new paragraph ends up in having duplicated paragraph inside the cell. Removing the original paragraph works fine.
Upvotes: 2