在平时的开发中可能遇到固定模板导出到word文档中的情况,这里简单介绍一种方法:
一、新建word模板
1.新建一个word文档:
2.编辑word文档,生成模板:
3.另存为,将word文档存成xml格式:
二、创建Spring Boot项目
1.创建spring boot项目,引入maven依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
2.创建application.yml配置文件,配置freemaker相关设置:
spring:
# 设置freemarker
freemarker:
allow-request-override: false
# 开发过程建议关闭缓存
cache: true
check-template-location: false
charset: UTF-8
content-type: text/html; charset=utf-8
expose-request-attributes: false
expose-session-attributes: false
expose-spring-macro-helpers: false
request-context-attribute:
# 默认后缀就是.ftl
suffix: .ftl
template-loader-path: classPath:/templates/
3.将xml文件拷贝到templates目录下,将后缀改成.ftl
4.编写一个controller测试是否能够导出word文档
@Controller
public class WordController {
@RequestMapping("test/doc")
@ResponseBody
public String exportDoc(User user) throws IOException {
Configuration configuration = new Configuration(Configuration.VERSION_2_3_0);
configuration.setDefaultEncoding("utf-8");
configuration.setClassForTemplateLoading(this.getClass(), "/templates/");
Template template = configuration.getTemplate("userinfo.ftl");
Map<String, Object> dataMap = new HashMap<>();
dataMap.put("name", user.getName());
dataMap.put("sex", user.getSex());
dataMap.put("age", user.getAge());
File outFile = new File("Test.doc");
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"));
try {
template.process(dataMap, out);
out.flush();
out.close();
} catch (TemplateException e) {
e.printStackTrace();
return "error";
}
return "success";
}
}
class User {
private String name;
private String sex;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
5.运行spring boot项目,访问:
http://localhost:8080/test/doc?name=张三&sex=男&age=23
6.刷新项目,根目录下出现导出的word文档:
7.打开word文档查看:
可以看到,word文档可以成功导出,核心就是借助freemarker模板技术,同理可以制作更为复杂的模板,也可以使用BASE64编码图片以后赋值到模板中,动态显示不同的图片,原理都差不多,不在赘述。