使用Apache POI在Docx中创建重复的表段落 [英] Duplicate Table Paragraphs in Docx created with Apache POI

查看:279
本文介绍了使用Apache POI在Docx中创建重复的表段落的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Apache POI来创建包含表的docx.

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?

推荐答案

问题已解决

重复是由document.createParagraph()引起的.

the duplication was caused by document.createParagraph().

我将方法更改为此:

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;
}

,现在一切正常.请注意cell.removeParagraph(0)

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.

这篇关于使用Apache POI在Docx中创建重复的表段落的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆