
<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;
}
}
}

- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59