Spring Boot中使用freeMarker生成word文档
Spring Boot中使用freeMarker生成word文档
前面介绍了Java POI方式来生成Word文档,今天用另一种方式来生成。使用freeMarker的方式来生成。使用freeMarker的方式来生成的过程具体如下。
在maven pom.xml文件中加入freeMarker,我这里是在maven环境下做的例子,用其他方式的小伙伴也可以直接到官网下载jar包。
- <!--添加freeMarker-->
- <dependency>
- <groupId>org.freemarker</groupId>
- <artifactId>freemarker</artifactId>
- <version>2.3.20</version>
- </dependency>
过程如下:
word文档:
然后将我们的word文档另存为xml文档。
将我们的xml文档的后缀改为ftl,然后用可以打开ftl文件的软件打开我们的ftl文件。在这里我们有几个需要注意的地方。
第一,定义的占位符可能会被分开了。就像下面这样:
我们需要做的就是删掉多余的部分,图中我定义的是${userName}.所以我就把多余的删掉,变成${userName}就可以了。
第二,我们需要注意的就是在我们的表格部分需要自己添加freeMarker标签。在表格代码间用自定的标签括起来。定义的参数要和我们在方法中定义的一致,否则无法取到值。
表格开始:
结束:
参数:
这样我们的模板就完成了。
将我们的模板文档放到我们的文件结构下就。但是Spring boot读取静态资源和其他方式的读取类型不一致哦,如果是Spring boot开发的小伙伴需要注意下一。不懂的自己去网上查阅一下就会明白了。其他方式的小伙伴根据自己的文件结构修改一下就好了。我这里的是直接放在resources文件夹下的。所以我这里的获取路径是这样写的。
Java代码如下:
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.InputStream;
- import java.net.URLDecoder;
- import java.text.SimpleDateFormat;
- import java.util.*;
- /**
- * Created by zhouhs on 2017/1/10.
- */
- @SuppressWarnings("serial")
- public class WordAction {
- private String filePath; //文件路径
- private String fileName; //文件名称
- private String fileOnlyName; //文件唯一名称
- public String createWord() {
- /** 用于组装word页面需要的数据 */
- Map<String, Object> dataMap = new HashMap<String, Object>();
- /** 组装数据 */
- dataMap.put("userName", "seawater");
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
- dataMap.put("date", sdf.format(new Date()));
- dataMap.put("content", "freeMark生成Word文档段落内容");
- List<Map<String, Object>> listInfo = new ArrayList<Map<String, Object>>();
- for (int i = 1; i <= 10; i++) {
- Map<String, Object> map = new HashMap<String, Object>();
- map.put("title", "标题" + i);
- map.put("content", "内容" + i);
- map.put("author", "作者" + i);
- listInfo.add(map);
- }
- dataMap.put("listInfo", listInfo);
- /** 文件名称,唯一字符串 */
- Random r = new Random();
- SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd");
- StringBuffer sb = new StringBuffer();
- sb.append(sdf1.format(new Date()));
- sb.append("_");
- sb.append(r.nextInt(100));
- //文件路径
- filePath = "D:/doc_f/";
- //文件唯一名称
- fileOnlyName = "用freemarker生成Word文档_" + sb + ".doc";
- //文件名称
- fileName = "用freemarker生成Word文档.doc";
- /** 生成word */
- WordUtil.createWord(dataMap, "freeMark.ftl", filePath, fileOnlyName);
- return "createWordSuccess";
- }
- /**
- *
- * 下载生成的word文档
- */
- public String dowloadWord() {
- /** 先判断文件是否已生成 */
- try {
- //解决中文乱码
- filePath = URLDecoder.decode(filePath, "UTF-8");
- fileOnlyName = URLDecoder.decode(fileOnlyName, "UTF-8");
- fileName = URLDecoder.decode(fileName, "UTF-8");
- //如果文件不存在,则会跳入异常,然后可以进行异常处理
- new FileInputStream(filePath + File.separator + fileOnlyName);
- } catch (Exception e) {
- e.printStackTrace();
- return "error";
- }
- return "dowloadWord";
- }
- /**
- * 返回最终生成的word文档 文件流
- * 下载生成的word文档
- */
- public InputStream getWordFile() {
- try {
- //解决中文乱码
- fileName = URLDecoder.decode(fileName, "UTF-8");
- /** 返回最终生成的word文件流 */
- return new FileInputStream(filePath + File.separator + fileOnlyName);
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- }
- }
- public String getFilePath() {
- return filePath;
- }
- public void setFilePath(String filePath) {
- this.filePath = filePath;
- }
- public String getFileName() {
- return fileName;
- }
- public void setFileName(String fileName) {
- this.fileName = fileName;
- }
- public String getFileOnlyName() {
- return fileOnlyName;
- }
- public void setFileOnlyName(String fileOnlyName) {
- this.fileOnlyName = fileOnlyName;
- }
- }
- import freemarker.template.Configuration;
- import freemarker.template.Template;
- import java.io.*;
- import java.util.Map;
- public class WordUtil {
- /**
- * 生成word文件
- * @param dataMap word中需要展示的动态数据,用map集合来保存
- * @param templateName word模板名称,例如:test.ftl
- * @param filePath 文件生成的目标路径,例如:D:/wordFile/
- * @param fileName 生成的文件名称,例如:test.doc
- */
- @SuppressWarnings("unchecked")
- public static void createWord(Map dataMap,String templateName,String filePath,String fileName){
- try {
- //创建配置实例
- Configuration configuration = new Configuration();
- //设置编码
- configuration.setDefaultEncoding("UTF-8");
- //ftl模板文件
- 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();
- }
- }
- }
生成的文档如下:
到这里我们在Spring boot中使用freeMarker生成word文档就完成了。
前面介绍了Java POI方式来生成Word文档,今天用另一种方式来生成。使用freeMarker的方式来生成。使用freeMarker的方式来生成的过程具体如下。
在maven pom.xml文件中加入freeMarker,我这里是在maven环境下做的例子,用其他方式的小伙伴也可以直接到官网下载jar包。
- <!--添加freeMarker-->
- <dependency>
- <groupId>org.freemarker</groupId>
- <artifactId>freemarker</artifactId>
- <version>2.3.20</version>
- </dependency>
过程如下:
word文档:
然后将我们的word文档另存为xml文档。
将我们的xml文档的后缀改为ftl,然后用可以打开ftl文件的软件打开我们的ftl文件。在这里我们有几个需要注意的地方。
第一,定义的占位符可能会被分开了。就像下面这样:
我们需要做的就是删掉多余的部分,图中我定义的是${userName}.所以我就把多余的删掉,变成${userName}就可以了。
第二,我们需要注意的就是在我们的表格部分需要自己添加freeMarker标签。在表格代码间用自定的标签括起来。定义的参数要和我们在方法中定义的一致,否则无法取到值。
表格开始:
结束:
参数:
这样我们的模板就完成了。
将我们的模板文档放到我们的文件结构下就。但是Spring boot读取静态资源和其他方式的读取类型不一致哦,如果是Spring boot开发的小伙伴需要注意下一。不懂的自己去网上查阅一下就会明白了。其他方式的小伙伴根据自己的文件结构修改一下就好了。我这里的是直接放在resources文件夹下的。所以我这里的获取路径是这样写的。
Java代码如下:
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.InputStream;
- import java.net.URLDecoder;
- import java.text.SimpleDateFormat;
- import java.util.*;
- /**
- * Created by zhouhs on 2017/1/10.
- */
- @SuppressWarnings("serial")
- public class WordAction {
- private String filePath; //文件路径
- private String fileName; //文件名称
- private String fileOnlyName; //文件唯一名称
- public String createWord() {
- /** 用于组装word页面需要的数据 */
- Map<String, Object> dataMap = new HashMap<String, Object>();
- /** 组装数据 */
- dataMap.put("userName", "seawater");
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
- dataMap.put("date", sdf.format(new Date()));
- dataMap.put("content", "freeMark生成Word文档段落内容");
- List<Map<String, Object>> listInfo = new ArrayList<Map<String, Object>>();
- for (int i = 1; i <= 10; i++) {
- Map<String, Object> map = new HashMap<String, Object>();
- map.put("title", "标题" + i);
- map.put("content", "内容" + i);
- map.put("author", "作者" + i);
- listInfo.add(map);
- }
- dataMap.put("listInfo", listInfo);
- /** 文件名称,唯一字符串 */
- Random r = new Random();
- SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd");
- StringBuffer sb = new StringBuffer();
- sb.append(sdf1.format(new Date()));
- sb.append("_");
- sb.append(r.nextInt(100));
- //文件路径
- filePath = "D:/doc_f/";
- //文件唯一名称
- fileOnlyName = "用freemarker生成Word文档_" + sb + ".doc";
- //文件名称
- fileName = "用freemarker生成Word文档.doc";
- /** 生成word */
- WordUtil.createWord(dataMap, "freeMark.ftl", filePath, fileOnlyName);
- return "createWordSuccess";
- }
- /**
- *
- * 下载生成的word文档
- */
- public String dowloadWord() {
- /** 先判断文件是否已生成 */
- try {
- //解决中文乱码
- filePath = URLDecoder.decode(filePath, "UTF-8");
- fileOnlyName = URLDecoder.decode(fileOnlyName, "UTF-8");
- fileName = URLDecoder.decode(fileName, "UTF-8");
- //如果文件不存在,则会跳入异常,然后可以进行异常处理
- new FileInputStream(filePath + File.separator + fileOnlyName);
- } catch (Exception e) {
- e.printStackTrace();
- return "error";
- }
- return "dowloadWord";
- }
- /**
- * 返回最终生成的word文档 文件流
- * 下载生成的word文档
- */
- public InputStream getWordFile() {
- try {
- //解决中文乱码
- fileName = URLDecoder.decode(fileName, "UTF-8");
- /** 返回最终生成的word文件流 */
- return new FileInputStream(filePath + File.separator + fileOnlyName);
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- }
- }
- public String getFilePath() {
- return filePath;
- }
- public void setFilePath(String filePath) {
- this.filePath = filePath;
- }
- public String getFileName() {
- return fileName;
- }
- public void setFileName(String fileName) {
- this.fileName = fileName;
- }
- public String getFileOnlyName() {
- return fileOnlyName;
- }
- public void setFileOnlyName(String fileOnlyName) {
- this.fileOnlyName = fileOnlyName;
- }
- }
- import freemarker.template.Configuration;
- import freemarker.template.Template;
- import java.io.*;
- import java.util.Map;
- public class WordUtil {
- /**
- * 生成word文件
- * @param dataMap word中需要展示的动态数据,用map集合来保存
- * @param templateName word模板名称,例如:test.ftl
- * @param filePath 文件生成的目标路径,例如:D:/wordFile/
- * @param fileName 生成的文件名称,例如:test.doc
- */
- @SuppressWarnings("unchecked")
- public static void createWord(Map dataMap,String templateName,String filePath,String fileName){
- try {
- //创建配置实例
- Configuration configuration = new Configuration();
- //设置编码
- configuration.setDefaultEncoding("UTF-8");
- //ftl模板文件
- 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();
- }
- }
- }
生成的文档如下:
到这里我们在Spring boot中使用freeMarker生成word文档就完成了。