- 使用Apache对doc文档进行填充
- 有些像合同之类的可能会用到对模板进行动态数据填充然后生成新的文档,下面就是我使用poi进行的doc文档填充的一些使用过程
- 模板很简单,使用时基本上都一样
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/3e6d87b0cce2a318bf3626050375d639.png)
- 依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.sunyw.xyz</groupId>
<artifactId>poitest</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<poi.version>4.1.2</poi.version>
<springboot.version>2.2.7.RELEASE</springboot.version>
</properties>
<dependencies>
<!--springboot-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<scope>compile</scope>
<version>${springboot.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>${springboot.version}</version>
</dependency>
<!--poi-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>${poi.version}</version>
</dependency>
</dependencies>
</project>
package com.sunyw.xyz.utils;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.Range;
import org.springframework.core.io.ClassPathResource;
import org.w3c.dom.Document;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import org.apache.poi.hwpf.HWPFDocument;
public class DocUtils {
private static final String upFileUrl = "D:/down/";
/**
* 替换.doc模板生成文件
*
* @param filePath 模板文件路径
* @param replace key为模板中被替换数据,value为替换数据
* @return fileName 生成的doc文件名称
* @author sunyw
*/
public String createDoc(String filePath, Map<String, String> replace) {
String fileName = null;
InputStream fileInputStream = null;
OutputStream outStream = null;
try {
fileInputStream = new ClassPathResource(filePath).getInputStream();
HWPFDocument doc = new HWPFDocument(fileInputStream);
Range range = doc.getRange();
Set<String> strings = replace.keySet();
for (String string : strings) {
//循环替换模板数据,key为被替换数据,value为替换后数据
range.replaceText(string, replace.get(string));
}
WordToHtmlConverter wordToHtmlConverter =
new WordToHtmlConverter(
DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
//解析doc
wordToHtmlConverter.processDocument(doc);
//文档生成
Document htmlDocument = wordToHtmlConverter.getDocument();
//生成文件名称
fileName = UUID.randomUUID() + ".doc";
File htmlFile = new File(upFileUrl + fileName);
outStream = new FileOutputStream(htmlFile);
DOMSource domSource = new DOMSource(htmlDocument);
StreamResult streamResult = new StreamResult(outStream);
TransformerFactory factory = TransformerFactory.newInstance();
Transformer serializer = factory.newTransformer();
serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
serializer.setOutputProperty(OutputKeys.METHOD, "html");
serializer.transform(domSource, streamResult);
} catch (Exception e) {
System.out.println("生成doc文件失败");
} finally {
try {
if (fileInputStream != null) {
fileInputStream.close();
}
if (outStream != null) {
outStream.close();
}
} catch (IOException e) {
e.getMessage();
}
}
return fileName;
}
}
package com.sunyw.xyz.service;
import com.sunyw.xyz.utils.DocUtils;
import java.util.HashMap;
import java.util.Map;
public class DocService {
public static void main(String[] args) {
System.out.println("------------------------<开始进行doc模板填充>------------------------");
Map<String, String> map = new HashMap<String, String>();
//商户名称
map.put("${jia}", "我是甲方");
//申请时间
map.put("${yi}", "我是乙方");
//发票个数
map.put("${date}", "2020-07-25");
DocUtils docUtils = new DocUtils();
String doc = docUtils.createDoc("/21.doc", map);
System.out.println(doc);
System.out.println("------------------------<doc模板填充完毕>------------------------");
}
}
- 执行结果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/c48acd4a4e9a9443a723f4ee672b7872.png)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/595467de22eea498cc6b4042d1bc92a2.png)
- 模板填充时需要定义一个标志位作为被替换的值,对应代码中的key值
- 码云地址:https://gitee.com/sunyaowei/poitest