Duplicate Table Paragraphs in Docx created with Apache POI

旧街凉风 提交于 2019-12-12 10:26:55

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/24660448/duplicate-table-paragraphs-in-docx-created-with-apache-poi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!