为 XWPFParagraph 设置背景颜色

Set background color for XWPFParagraph

我想更改段落的背景颜色,但我找不到如何操作的方法。我只能找到如何突出显示单词。我希望我的文字看起来像

你的截图不是很清楚。它可以显示多个不同的东西。但是当你谈论 Word 段落时,我怀疑它显示了一个有边框和阴影的段落。

以下代码创建了一个 Word 文档,其中的段落具有边框和底纹。边框设置可以使用XWPFParagraph的方法实现。直到现在才提供阴影设置。因此需要底层 ooxml-schemas 的方法和 类。

import java.io.FileOutputStream;

import org.apache.poi.xwpf.usermodel.*;

public class CreateWordParagraphBackground {

 private static void setParagraphShading(XWPFParagraph paragraph, String rgb) {
  if (paragraph.getCTP().getPPr() == null) paragraph.getCTP().addNewPPr();
  if (paragraph.getCTP().getPPr().getShd() != null) paragraph.getCTP().getPPr().unsetShd();
  paragraph.getCTP().getPPr().addNewShd();
  paragraph.getCTP().getPPr().getShd().setVal(org.openxmlformats.schemas.wordprocessingml.x2006.main.STShd.CLEAR);
  paragraph.getCTP().getPPr().getShd().setColor("auto");
  paragraph.getCTP().getPPr().getShd().setFill(rgb);
 }

 public static void main(String[] args) throws Exception {

  XWPFDocument document = new XWPFDocument();

  XWPFParagraph paragraph = document.createParagraph();
  XWPFRun run = paragraph.createRun();  
  run.setText("Folollowing paragraph with border and shading:");

  paragraph = document.createParagraph();  
  paragraph.setBorderLeft(Borders.SINGLE);
  paragraph.setBorderTop(Borders.SINGLE);
  paragraph.setBorderRight(Borders.SINGLE);
  paragraph.setBorderBottom(Borders.SINGLE);

  setParagraphShading(paragraph, "BFBFBF");

  run = paragraph.createRun();  
  run.setText("Lorem ipsum dolor sit amet, consetetur sadipscing elitr, ");
  run = paragraph.createRun();
  run.addBreak(BreakType.TEXT_WRAPPING);
  run.setText("sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.");
  run.addBreak(BreakType.TEXT_WRAPPING);

  paragraph = document.createParagraph();

  FileOutputStream out = new FileOutputStream("CreateWordParagraphBackground.docx");
  document.write(out);
  out.close();
  document.close();
 }
}