参考资料
具体的代码参考
一、Maven中pom文件引入
<!-- https://mvnrepository.com/artifact/org.freemarker/freemarker -->
<!-- word 模板引擎 -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.30</version>
</dependency>
二、编写代码前的步骤
- 首先创建好对应的word模板
- 根据word模板,把模板另存为XML 文件
- windows 记事本打开对应的文件,另存为 ftl 格式的文件
- 最后把 ftl 后缀的文件添加到项目中
三、通过Main方法调用生成对应的word文档
public static void main(String[] args) throws IOException, TemplateException {
// 1.创建配置
Configuration configuration = new Configuration(Configuration.VERSION_2_3_30);
// 2.加载模板
String filePath = "D:\\code\\project\\projcet-controller\\src\\main\\resources" +
"\\wordtemplete";
configuration.setDirectoryForTemplateLoading(new File(filePath));
// 3.设置编码格式
String encoding = "UTF-8";
configuration.setDefaultEncoding(encoding);
// 4.设置模板异常类型
configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
// 5.创建数据类型
Map<String, Object> root = new HashMap<>();
root.put("name", "张三");
root.put("sex", "男");
root.put("age", "18");
root.put("sechool", "家里蹲");
root.put("major", "家庭宅男");
root.put("company", "家");
// 6.获取模板
Template temp = configuration.getTemplate("test.ftl");
// 7.输出 重新生成word 文档
Writer out = null;
try {
File outFile = new File("D:/test.doc");
if (outFile.exists()){
outFile.delete();
}
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"UTF-8"));
temp.process(root, out);
} finally {
out.close();
}
四、通过浏览器的访问,生成对应的word文档
- controller层代码
@GetMapping("/download")
public String getwordFile(@Param("name") String name, @Param("wordTemplateName") String wordTemplateName,
HttpServletResponse response) {
// 获取模板所在的项目文件路径
String path = ClassUtils.getDefaultClassLoader().getResource("wordtemplate").getPath();
String templateName = "test.ftl";
Map<String, Object> resultMap = new HashMap<>();
resultMap.put("name", name);
resultMap.put("sex", "男");
resultMap.put("age", "18");
resultMap.put("sechool", "家里蹲");
resultMap.put("major", "家庭宅男");
resultMap.put("company", "家");
try {
CreatWordUtils.creadWordFileInBrower(response, path, templateName, resultMap);
} catch (Exception e) {
e.printStackTrace();
}
return "下载成功";
}
- common层代码
public static void creadWordFileInBrower(HttpServletResponse response, String filePath, String tempalteName,
Map<String, Object> resultMap) throws Exception {
Template temp = getTemplate(filePath, tempalteName);
File file = null;
InputStream fin = null;
ServletOutputStream out = null;
try {
// 调用工具类的createDoc方法生成Word文档
file = createFile(temp, resultMap);
fin = new FileInputStream(file);
response.setCharacterEncoding("utf-8");
response.setContentType("application/msword");
// 设置浏览器以下载的方式处理该文件名
String fileName = "TEST_" + String.valueOf(System.currentTimeMillis()) + ".doc";
response.setHeader("Content-Disposition", "attachment;filename=".concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8"))));
out = response.getOutputStream();
// 缓冲区
byte[] buffer = new byte[512];
int bytesToRead = -1;
// 通过循环将读入的Word文件的内容输出到浏览器中
while ((bytesToRead = fin.read(buffer)) != -1) {
out.write(buffer, 0, bytesToRead);
}
} finally {
if (fin != null) {
fin.close();
}
if (out != null) {
out.close();
}
if (file != null) {
file.delete();
}// 删除临时文件
}
}
private static Template getTemplate(String filePath, String tempalteName) throws IOException {
// 1.创建配置
Configuration configuration = new Configuration(Configuration.VERSION_2_3_30);
// 2.加载模板
configuration.setDirectoryForTemplateLoading(new File(filePath));
// 3.设置编码格式
String encoding = "UTF-8";
configuration.setDefaultEncoding(encoding);
// 4.设置模板异常类型
configuration.setTemplateExceptionHandler(TemplateExceptionHandler.DEBUG_HANDLER);
// 6.获取模板
Template temp = configuration.getTemplate(tempalteName);
return temp;
}
private static File createFile(Template temp, Map<String, Object> map) {
String saveAllPath = "temp" + String.valueOf(System.currentTimeMillis()) + ".doc";
// 7.输出 重新生成word 文档
Writer out = null;
File outFile = new File(saveAllPath);
try {
if (outFile.exists()) {
outFile.delete();
}
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"));
// 根据数据输出
temp.process(map, out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
return outFile;
}