如何使用 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?

查看:38
本文介绍了如何使用 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,完整的 https://poi中所述,需要ooxml-schemas-1.3.jar.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天全站免登陆