Java poi给docx中的关键字标记颜色
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.14.3</version>
</dependency>
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
public class HtmlToDocxConverter {
public static void main(String[] args) {
File file = new File("C:\\temp\\test.docx");
try {
FileInputStream fis = new FileInputStream(file);
XWPFDocument xdoc = new XWPFDocument(fis);
String key = "遗嘱";
String color = "ff0000";
int size = xdoc.getParagraphs().size();
for (int i1 = 0; i1 < size; i1++) {
XWPFParagraph paragraph = xdoc.createParagraph();
String end = generator(paragraph,key,color, xdoc.getParagraphs().get(i1).getText());
paragraph.createRun().setText(end);
}
for (int j = 0; j < size; j++) {
xdoc.removeBodyElement(0);
}
OutputStream os= new FileOutputStream("C:\\temp\\test2.docx");
xdoc.write(os);
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private static String generator(XWPFParagraph paragraph,String key,String color,String s) {
String end = splitStr(s,key);
if (s.contains(key)) {
String begin = "";
begin = s.substring(0, s.indexOf(key));
paragraph.createRun().setText(begin);
XWPFRun run = paragraph.createRun();
run.setText(key);
run.setColor(color);
return generator(paragraph,key,color,end);
} else {
return end;
}
}
private static String splitStr(String content,String key) {
if (content.contains(key)) {
return content.substring(content.indexOf(key) + key.length());
} else {
return content;
}
}
}