如何在 Java 中为 word 文档(.doc 或 .docx)设置背景颜色(页面颜色)?

问题描述:

通过像http://poi.apache.org这样的库,我们可以创建word文档 任何文本颜色,但对于文本的背景或突出显示,我没有找到任何解决方案.

By some libraries like http://poi.apache.org , we could create word document with any text color, but for background or highlight of the text, I didn't find any solution.

手动方式为 word 页面颜色!:

Page color for word in manual way!:

https://support.office.com/en-us/article/Change-the-background-or-color-of-a-document-6ce0b23e-b833-4421-b8c3-b3d637e62524

这是我用poi.apache创建word文档的主要代码

Here is my main code to create word document by poi.apache

        // Blank Document
        @SuppressWarnings("resource")
        XWPFDocument document = new XWPFDocument();
        // Write the Document in file system
        FileOutputStream out = new FileOutputStream(new File(file_address));
        // create Paragraph
        XWPFParagraph paragraph = document.createParagraph();
        paragraph.setAlignment(ParagraphAlignment.RIGHT);

        XWPFRun run = paragraph.createRun();
        run.setFontFamily(font_name);
        run.setFontSize(font_size);
        // This only set text color not background!
        run.setColor(hex_color);

        for (String s : text_array) {
            run.setText(s);
            run.addCarriageReturn();
        }

        document.write(out);
        out.close();

我们只需要添加这 3 行就可以通过 XWPF 设置 Word 文档的背景颜色.我们必须在声明 XWPFRun 和它的文本颜色后设置这些行:

We Only need to add these 3 lines to set the background color for Word documents by XWPF. We have to set these lines after declaring XWPFRun and it's text color:

CTShd cTShd = run.getCTR().addNewRPr().addNewShd();
cTShd.setVal(STShd.CLEAR);
cTShd.setFill(hex_background_color);