使用SpringBoot+freemaker实现word导出功能
1、引入pom依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
2、加入工具类
package com.jt.www.util.mail;
import freemarker.template.Configuration;
import freemarker.template.Template;
import java.io.*;
import java.util.Map;
/**
* @Description: 生成Word工具类
* @author: xuxinku
* @Date: 2019/6/16 9:42
* @ModifiedDate:
* @Copyright:XX保险股份有限公司
*/
public class WordUtil {
/**
* @Desc:生成word文件
* @Author:xuxinke
* @Date:2019/6/16 9:42
* @param dataMap word中需要展示的动态数据,用map集合来保存
* @param templateName word模板名称,例如:06test.ftl
* @param filePath 文件生成的目标路径,例如:D:/wordFile/
* @param fileName 生成的文件名称,例如:test.doc
*/
@SuppressWarnings("unchecked")
public static String createWord(Map dataMap, String templateName, String filePath, String fileName){
try {
//创建配置实例
Configuration configuration = new Configuration(Configuration.VERSION_2_3_23);
//设置编码
configuration.setDefaultEncoding("UTF-8");
//ftl模板文件统一放至 com.lun.template 包下面
// D:\ideas\JTJBW\edu-svc\src\main\resources\templates
configuration.setClassForTemplateLoading(WordUtil.class,"/");
//获取模板
Template template = configuration.getTemplate(templateName);
//输出文件
File outFile = new File(filePath+ File.separator+fileName);
//如果输出目标文件夹不存在,则创建
if (!outFile.getParentFile().exists()){
outFile.getParentFile().mkdirs();
}
//将模板和数据模型合并生成文件
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"UTF-8"));
//生成文件
template.process(dataMap, out);
//关闭流
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
String WJ=filePath+fileName;
return WJ;
}
}
3、创建ftl模板文件
3.1创建Word文件定义好变量保存为xml格式
3.2重命名为.ftl文件
4.调用工具类生成word文件
4.1 导出word功能
@GetMapping("wordTest")
public String wordTest(){
/** 用于组装word页面需要的数据 */
Map<String, String> dataMap = new HashMap<String, String>();
dataMap.put("post_name","Java开发工程师");
dataMap.put("adjustment","是");
dataMap.put("name","小张");
dataMap.put("sex","男");
dataMap.put("nation","汉族");
dataMap.put("height","172cm");
dataMap.put("zzmm","共青团员");
dataMap.put("native_place","福建省南平市");
dataMap.put("marriage","未婚");
dataMap.put("sfjhm","1313154564684684234");
dataMap.put("birth","1999-01-20");
dataMap.put("title","高级Java开发工程师");
dataMap.put("title_time","2023-03-15");
dataMap.put("phone","13629538953");
dataMap.put("email","227154@");
dataMap.put("school_time","2021-06-01");
dataMap.put("school","厦门工学院");
dataMap.put("most_academic","本科");
dataMap.put("chat_address","xx省xx市xxx");
dataMap.put("foreign","CET4");
dataMap.put("computer","4级");
dataMap.put("specialty","篮球");
dataMap.put("now_salary","6000");
dataMap.put("except_salary","8000");
dataMap.put("xxsource","boss直聘");
//String filePath = "D:/JB/";
//String filePath =System.getProperty("java.io.tmpdir")+ File.separator;
String filePath = "E:\\";
System.out.println("查看临时路径=======》"+filePath);
//文件唯一名称
String fileOnlyName = "ccc.doc";
/** 生成word 数据包装,模板名,文件生成路径,生成的文件名*/
String WJ = WordUtil.createWord(dataMap, "c.ftl", filePath, fileOnlyName);
return WJ;
}
4.2 下载word功能
/**
* 平台实现更新包下载
*
* @param request
* @param response
* @return
*/
@RequestMapping("/download")
public String downloadFile(HttpServletRequest request,
HttpServletResponse response, String fileFullName) throws UnsupportedEncodingException {
// String rootPath = propertiesconfig.getUploadpacketPath();//这里是我在配置文件里面配置的根路径,各位可以更换成自己的路径之后再使用(例如:D:/test)
String rootPath = "E://";
String FullPath = rootPath + fileFullName;//将文件的统一储存路径和文件名拼接得到文件全路径
File packetFile = new File(FullPath);
String fileName = packetFile.getName(); //下载的文件名
File file = new File(FullPath);
// 如果文件名存在,则进行下载
if (file.exists()) {
// 配置文件下载
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream");
// 下载文件能正常显示中文
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
// 实现文件下载
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
System.out.println("Download the song successfully!");
} catch (Exception e) {
System.out.println("Download the song failed!");
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} else {//对应文件不存在
try {
//设置响应的数据类型是html文本,并且告知浏览器,使用UTF-8 来编码。
response.setContentType("text/html;charset=UTF-8");
//String这个类里面, getBytes()方法使用的码表,是UTF-8, 跟tomcat的默认码表没关系。 tomcat iso-8859-1
String csn = Charset.defaultCharset().name();
System.out.println("默认的String里面的getBytes方法使用的码表是: " + csn);
//1. 指定浏览器看这份数据使用的码表
response.setHeader("Content-Type", "text/html;charset=UTF-8");
OutputStream os = response.getOutputStream();
os.write("对应文件不存在".getBytes());
} catch (IOException e) {
e.printStackTrace();
}
// return R.error("-1","对应文件不存在");
}
return null;
}
5、效果展示
ps:有个需要注意的地方, 由于freemarker的是用xml来生成的Word , 导致很多手机软件打开是乱码的 ,手机软件不能识别 xml格式的文档, 这个我也很头疼, 有能解决的大神可以私信或者评论下 互相学习。