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

时间:2016-10-29 11:13:05

标签: java apache-poi xwpf

当前输出: img

需要的输出: img2

以上是.docx的快照,以下是代码示例代码,我想在a替换后更改@的颜色。 r.setColor("DC143C")无效:

for (XWPFParagraph p : docx.getParagraphs()) {
        List<XWPFRun> 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);
                }
            }
        }
    }

1 个答案:

答案 0 :(得分:4)

如果需要更改一个字符的颜色,则此字符必须在其自己的运行中。这是因为只能运行样式。

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

示例:

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

 }
}