java poi修改word2007_java – 如何使用apache poi更改特定word文档的颜色?

本文介绍了如何使用Java的Apache POI库修改Word2007(.docx)文档中的文本颜色。当查找并替换特定字符如"a"时,必须确保每个字符都在独立的运行(run)中,以便为每个字符设置不同的样式。通过遍历文档的段落和运行,插入新的运行来实现颜色更改,并最终保存到新的文档。
摘要由CSDN通过智能技术生成

当前输出:

gCAKo.jpg

需要的输出:

Ev1hL.jpg

上面是.docx的快照,下面是代码示例代码,我希望在用@替换之后更改a的颜色. r.setColor(“DC143C”)不起作用:

for (XWPFParagraph p : docx.getParagraphs()) {

List runs = p.getRuns();

if (runs != null) {

for (XWPFRun r : runs) {

String origText = r.getText(0);

if (origText != null && origText.contains("a")) {

origText = origText.replace("a", "@");

r.setText(origText, 0);

}

}

}

}

解决方法:

如果需要改变一个字符的颜色,那么这个字符必须在它自己的运行中.这是因为只能运行样式.

如果您有一个包含文本的文档,则必须运行所有已存在的运行,并可能将这些运行拆分为多个运行.结果,每个应该单独设置样式的字符串部分必须在它自己的运行中,如果它只是一个字符.

例:

import java.io.*;

import org.apache.poi.xwpf.usermodel.*;

import java.awt.Desktop;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;

public class WordReadAndWrite {

public static void main(String[] args) throws IOException, InvalidFormatException {

XWPFDocument doc = new XWPFDocument(new FileInputStream("source.docx"));

for (XWPFParagraph p : doc.getParagraphs()) { //go through all paragraphs

int runNumber = 0;

while (runNumber < p.getRuns().size()) { //go through all runs, we cannot use for each since we will possibly insert new runs

XWPFRun r = p.getRuns().get(runNumber);

String runText = r.getText(0);

if (runText != null && runText.contains("a")) { //if we have a run with an "a" in it, then

char[] runChars = runText.toCharArray();

StringBuffer sb = new StringBuffer();

for (int charNumber = 0; charNumber < runChars.length; charNumber++) { //go through all characters in that run

if (runChars[charNumber] == 'a') { //if the charcter is an 'a' then

r.setText(sb.toString(), 0); //set all characters, which are current buffered, as the text of the actual run

r = p.insertNewRun(++runNumber); //insert new run for the '@' as the replacement for the 'a'

r.setText("@", 0);

r.setColor("DC143C");

r = p.insertNewRun(++runNumber); //insert new run for the next characters

sb = new StringBuffer(); //empty buffer

} else {

sb.append(runChars[charNumber]); //buffer all characters which are not 'a's

}

}

r.setText(sb.toString(), 0); //set all characters, which are current buffered, as the text of the actual run

}

runNumber++;

}

}

doc.write(new FileOutputStream("result.docx"));

doc.close();

System.out.println("Done");

Desktop.getDesktop().open(new File("result.docx"));

}

}

标签:java,apache-poi,xwpf

来源: https://codeday.me/bug/20190623/1267149.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值