设置XWPFParagraph的背景颜色

问题描述

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

enter image description here

中看起来像

解决方法

您的屏幕截图不太清楚。它可以显示多种不同的事物。但是,当您谈论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();
 }
}