Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
505 views
in Technique[技术] by (71.8m points)

xwpf - How can I set background colour of a run (a word in line or a paragraph) in a docx file by using Apache POI?

I want to create a docx file by using Apache POI.

I want to set background colour of a run (i.e. a word or some parts of a paragraph).

How can I do this?

Is in possible via Apache POI or not.

Thanks in advance

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Word provides two possibilities for this. There are really background colors possible within runs. But there are also so called highlighting settings.

With XWPF both possibilities are only possible using the underlying objects CTShd and CTHighlight. But while CTShd is shipped with the default poi-ooxml-schemas-3.13-...jar, for the CTHighlight the fully ooxml-schemas-1.3.jar is needed as mentioned in https://poi.apache.org/faq.html#faq-N10025.

Example:

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"));

 }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...