Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/u010996565/article/details/87907356
Use FreeMarker Export world, download function under SpringBoot
Export documents in the Java World, the earliest before using POI, due to the more complicated, the use FreeMarker template to operate, more convenient. Straight to the bar
1. Prepare to export template document![Here Insert Picture Description](https://img-blog.csdnimg.cn/20190224200745174.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTA5OTY1NjU=,size_16,color_FFFFFF,t_70)
2. Save it as xml format
3. The xml file suffix into .ftl, then copied to the project
After the format is like this
4. Preparation Tools
First, add the jar FreeMarker package dependencies,
<!--引入freemarker 模板依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
Tools 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. Test
Download the results shown in Figure: