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

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

手动方式的单词页面颜色!:

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

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

// 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(); 

更新:XWPF是创建word文档文件的最新方式,但只能通过旧格式版本(.doc)的HWPF设置后台

对于* .doc(即POI的HWPF组件):

  1. 突出显示文本:查看setHighlighted()

  2. 背景颜色:

    我想你的意思是段落的背景(AFAIK,Word也允许为整个页面着色,这是另一回事)

    有一个setShading()允许您为setShading()提供前景色和背景色(通过setCvFore()setCvBack() )。 IIRC,它是您想要设置的前景 ,以便为段落着色。 背景仅与由两种(交替)颜色组成的阴影相关。

    基础数据结构名为Shd80 ([MS-DOC],2.9.248)。 还有SHDOperand ([MS-DOC],2.9.249),它反映了Word97之前Word的function。 [MS-DOC]是二进制Word文件格式规范,可在MSDN上免费获取。

编辑:

以下是一些代码来说明以上内容:

  try { HWPFDocument document = [...]; // comes from somewhere Range range = document.getRange(); // Background shading of a paragraph ParagraphProperties pprops = new ParagraphProperties(); ShadingDescriptor shd = new ShadingDescriptor(); shd.setCvFore(Colorref.valueOfIco(0x07)); // yellow; ICO shd.setIpat(0x0001); // solid background; IPAT pprops.setShading(shd); Paragraph p1 = range.insertBefore(pprops, StyleSheet.NIL_STYLE); p1.insertBefore("shaded paragraph"); // Highlighting of individual characters Paragraph p2 = range.insertBefore(new ParagraphProperties(), StyleSheet.NIL_STYLE); CharacterRun cr = p2.insertBefore("highlighted text\r"); cr.setHighlighted((byte) 0x06); // red; ICO document.write([...]); // document goes to somewhere } catch (IOException e) { e.printStackTrace(); } 
  • ICO是一种颜色结构
  • IPAT是预定义着色样式的列表

我们只需要添加这3行来为XWPF设置Word文档的背景颜色。 在声明XWPFRun及其文本颜色后,我们必须设置这些行:

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