2

我想使用 Apache POI 创建一个 docx 文件。

我想设置运行的背景颜色(即一个单词或段落的某些部分)。

我怎样才能做到这一点?

是否可以通过 Apache POI。

提前致谢

4

1 回答 1

8

Word 为此提供了两种可能性。在运行中确实有可能的背景颜色。但也有所谓的高亮设置。

只有使用XWPF底层对象CTShdCTHighlight. 但是,虽然CTShd附带了 default poi-ooxml-schemas-3.13-...jar,但正如https://poi.apache.org/faq.html#faq-N10025CTHighlight中所述,需要完全。ooxml-schemas-1.3.jar

例子:

import java.io.FileOutputStream;

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

import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTShd;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STShd;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STHighlightColor;
/*
To
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STHighlightColor;
the fully ooxml-schemas-1.3.jar is needed as mentioned in https://poi.apache.org/faq.html#faq-N10025
*/

public class WordRunWithBGColor {

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

  XWPFDocument doc= new XWPFDocument();

  XWPFParagraph paragraph = doc.createParagraph();
  XWPFRun run=paragraph.createRun();  
  run.setText("This is text with ");

  run=paragraph.createRun();  
  run.setText("background color");
  CTShd cTShd = run.getCTR().addNewRPr().addNewShd();
  cTShd.setVal(STShd.CLEAR);
  cTShd.setColor("auto");
  cTShd.setFill("00FFFF");

  run=paragraph.createRun();  
  run.setText(" and this is ");

  run=paragraph.createRun();  
  run.setText("highlighted");
  run.getCTR().addNewRPr().addNewHighlight().setVal(STHighlightColor.YELLOW);

  run=paragraph.createRun();  
  run.setText(" text.");

  doc.write(new FileOutputStream("WordRunWithBGColor.docx"));

 }
}
于 2016-02-19T14:56:57.000 回答