如何使用Apache POI在docx文件中设置运行(行中的单词或段落)的背景颜色? [英] How can I set background colour of a run (a word in line or a paragraph) in a docx file by using Apache POI?

查看:431
本文介绍了如何使用Apache POI在docx文件中设置运行(行中的单词或段落)的背景颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Apache POI创建docx文件.

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).

我该怎么做?

是否可以通过Apache POI.

Is in possible via Apache POI or not.

预先感谢

推荐答案

Word为此提供了两种可能性.运行中确实可能存在背景颜色.但是也有所谓的突出显示设置.

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

对于XWPF,这两种可能性只有使用基础对象CTShdCTHighlight才有可能.但是,尽管CTShd随附了默认的poi-ooxml-schemas-3.13-...jar,但对于CTHighlight,需要完整的ooxml-schemas-1.3.jar,如 https://poi.apache.org/faq.html#faq-N10025 .

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.

示例:

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

 }
}

这篇关于如何使用Apache POI在docx文件中设置运行(行中的单词或段落)的背景颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆