SpringBoot下使用FreeMarker导出world,下载功能
SpringBoot下使用FreeMarker导出world,下载功能
Java中导出World文档,最早之前使用的是POI,由于比较繁琐,这次改用FreeMarker模板来进行操作,比较方便。 直奔主题吧
1.准备要导出的模板文档
2.将其另存为xml格式
3.将该xml文件后缀改成.ftl,然后拷贝到项目中
进行格式化之后就是这个样子
4.编写工具类
首先在添加FreeMarker的jar包依赖、
<!--引入freemarker 模板依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
工具类 WorldUtil.java
import freemarker.template.Configuration;
import freemarker.template.Template;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.OutputStreamWriter;
import java.net.URLEncoder;
import java.util.Map;
/**
* world工具类
*
* @author cheny
* @version 1.0
* @create 2019-02-13 17:13
**/
public class WorldUtil {
/**
* 导出world
* @param dataMap 数据集
* @param templateName 模板名称
* @param filePath 模板路径
* @param fileName 文件名
* @param response
*/
public static void exportDoc(Map dataMap, String templateName, String filePath, String fileName, HttpServletResponse response){
try {
Configuration configuration = new Configuration();
configuration.setDefaultEncoding("UTF-8");
//设置模板所在文件夹
configuration.setDirectoryForTemplateLoading(new File(filePath));
//获取模板
Template template = configuration.getTemplate(templateName);
// 告诉浏览器用什么软件可以打开此文件
response.setHeader("Content-disposition",
"attachment;filename=" + URLEncoder.encode(fileName + ".doc", "UTF-8"));
response.setContentType("application/msword");// 定义输出类型
template.process(dataMap, new OutputStreamWriter(response.getOutputStream()));
} catch (Exception e){
e.printStackTrace();
}
}
}
5.测试
下载结果如图: