2
我想通過使用Apache POI創建一個docx文件。如何使用Apache POI在docx文件中設置運行的背景顏色(一行或一段文字)?
我想設置跑步的背景顏色(即單詞或段落的某些部分)。
我該怎麼做?
通過Apache POI是否可行。
在此先感謝
我想通過使用Apache POI創建一個docx文件。如何使用Apache POI在docx文件中設置運行的背景顏色(一行或一段文字)?
我想設置跑步的背景顏色(即單詞或段落的某些部分)。
我該怎麼做?
通過Apache POI是否可行。
在此先感謝
Word爲此提供了兩種可能性。運行過程中可能會有背景顏色。但也有所謂的高亮設置。
隨着XWPF
這兩種可能性只能使用基礎對象CTShd
和CTHighlight
。但是,CTShd
隨缺省poi-ooxml-schemas-3.13-...jar
一起發貨,對於CTHighlight
,需要完整ooxml-schemas-1.3.jar
,如https://poi.apache.org/faq.html#faq-N10025中所述。
實施例:
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"));
}
}
[本](http://stackoverflow.com/a/34544181/5717099)可以HWPF溶液。不過,我不確定是否可以使用XWPF。 – morido