如何使用 Apache POI 在文档文件中设置运行的背景颜色

该博客演示了如何利用Apache POI库在Java程序中创建一个Word文档,并为文本设置背景颜色以及高亮显示。通过示例代码,展示了如何设置CTShd和STHighlightColor来实现这些效果。
摘要由CSDN通过智能技术生成

 

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

 }
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值