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

查看:36
本文介绍了使用 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;
}

我调用方法:

        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天全站免登陆