Java uses word templates to generate word files (SpringBoot can be used)
1. Principle
Use a written word document template, query the content written in the document field, replace the template that needs to be replaced in the document field, and then generate a new word template.
Templates: Use "${}" in templates as a text
generator effect to change the padding of the replacement:
Two, the code
java code
public void downloadWord(Map<String, String> contentMap, String fileName) {
String tmpFile = "static/doc/ar_template.doc";
String fileType = ".doc";
InputStream inputStream = EconomicPersonnelService.class.getClassLoader().getResourceAsStream(tmpFile);//获取模板的inputstream
//InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(tmpFile);
HWPFDocument document = null;
try {
document = new HWPFDocument(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
// 读取文本内容
Range bodyRange = document.getRange();
// 替换内容
Iterator iter = contentMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
Object key = entry.getKey();
Object value = entry.getValue();
System.out.println(key);
System.out.println(value);
}
for (Map.Entry<String, String> entry : contentMap.entrySet()) {
bodyRange.replaceText("${" + entry.getKey() + "}", entry.getValue());
}
//导出到文件
try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
document.write(byteArrayOutputStream);
String path = Thread.currentThread().getContextClassLoader().getResource("").getPath() + "static/doc/";//获取resource下static/doc/的路径
OutputStream outputStream = new FileOutputStream(path + fileName + fileType);//路径+文件名+后缀
outputStream.write(byteArrayOutputStream.toByteArray());//生成写入
outputStream.close();//关闭输出流
} catch (IOException e) {
e.printStackTrace();
}
}
Front-end parameter passing
$.ajax({
url: MODULE_PATH2 + '/downloadWord',
dataType: 'json',
data: {
"dwmc": data.dwmc,
"leader": data.leader,
"auditors": data.auditors,
"t_date_start": data.t_date_start,
"t_date_end": data.t_date_end,
"nowDate": data.nowDate,
"nowDateAdd": data.nowDateAdd,
"position": data.position,
"fileName": "手动表单查询涵" //根据模板生成的word文档名字
},
The "key" value in front of the label needs to be the same as the field filled in the word template "${}"