java导出word
演示网站:编号0002
前提准备:
-
导入freemarker的jar包
-
获取ftl模板
-
导入freemarker的jar包
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.28</version>
</dependency>
- 获取ftl模板
新建一个word模板,使用${*}
进行占位,*为是字段定义的名称,如下所示
word:
user对象:
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
// id
private String id;
// 用户名
private String username;
// 密码
private String password;
// 性别
private String sex;
}
然后将word另存为xml
格式(注:不要直接修改文件后缀,另保存内有xml格式),然后将.xml
的后缀直接修改为.ftl
如果导入一个用户,不需要循环遍历不需要修改user.ftl文件
,若导出列表需要循环,需要进行对ftl
模板进行修改。
原始的user.ftl
文件如下,很难看清文件格式
使用xml在线格式化(百度搜索)进行格式化一下,如下图所示:
其中:
w:tbl 表格开始标志
w:tblPr 表格属性
w:tr 表格加一行
w:tc 表格加一列
<#list 要循环的数据 as 循环后的数据>
</#list>
如:
<#list userList as user>
${user.id}
</#list>
后端代码:
@GetMapping("/export")
public void exportWord(HttpServletResponse response) {
// 数据库查出的数据
List<User> users = userService.queryList();
// 获取导出的word模板
String path = this.getClass().getClassLoader().getResource("files").getPath();
File file = new File(path);
// Configuration 用于读取ftl文件
Configuration configuration = new Configuration(new Version("2.3.0"));
configuration.setDefaultEncoding("utf-8");
// 设置response的hear,导出word
PrintWriter out = null;
try
{
configuration.setDirectoryForTemplateLoading(file); //指定路径
Template template = configuration.getTemplate("user.ftl","utf-8");
String fileName = URLEncoder.encode("用户列表.doc", "UTF-8");
response.setContentType("application/msword");
response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
response.setCharacterEncoding("utf-8");//此句非常关键,不然word文档全是乱码
out = response.getWriter();
template.process(users, out);
}catch (Exception e)
{
e.printStackTrace();
} finally {
if(Objects.nonNull(out)) {
out.flush();
out.close();
}
}
}
前端代码:
window.location.href = 'xxxxx/xxxxx/export'