Spring Boot中使用freeMarker生成word文档 Spring Boot中使用freeMarker生成word文档

Spring Boot中使用freeMarker生成word文档

前面介绍了Java POI方式来生成Word文档,今天用另一种方式来生成。使用freeMarker的方式来生成。使用freeMarker的方式来生成的过程具体如下。

在maven pom.xml文件中加入freeMarker,我这里是在maven环境下做的例子,用其他方式的小伙伴也可以直接到官网下载jar包。

[html]  view plain  copy
  1. <!--添加freeMarker-->  
  2.         <dependency>  
  3.             <groupId>org.freemarker</groupId>  
  4.             <artifactId>freemarker</artifactId>  
  5.             <version>2.3.20</version>  
  6.         </dependency>  
下一步我们要做的是先好我们的word模板然后将模板转换为xml文件。在word模板中需要定义好我们的占位符哦,使用${string}的方式。“string”根据自己的爱好定义就好了。

过程如下:

word文档:

word-1

然后将我们的word文档另存为xml文档。

xml-1
将我们的xml文档的后缀改为ftl,然后用可以打开ftl文件的软件打开我们的ftl文件。在这里我们有几个需要注意的地方。

第一,定义的占位符可能会被分开了。就像下面这样:

zwf-1

我们需要做的就是删掉多余的部分,图中我定义的是${userName}.所以我就把多余的删掉,变成${userName}就可以了。

第二,我们需要注意的就是在我们的表格部分需要自己添加freeMarker标签。在表格代码间用自定的标签括起来。定义的参数要和我们在方法中定义的一致,否则无法取到值。

表格开始:

list-1

结束:

list-2

参数:

p-1

这样我们的模板就完成了。

将我们的模板文档放到我们的文件结构下就。但是Spring boot读取静态资源和其他方式的读取类型不一致哦,如果是Spring boot开发的小伙伴需要注意下一。不懂的自己去网上查阅一下就会明白了。其他方式的小伙伴根据自己的文件结构修改一下就好了。我这里的是直接放在resources文件夹下的。所以我这里的获取路径是这样写的。

r-1

r-2

Java代码如下:

[java]  view plain  copy
  1. import java.io.File;  
  2. import java.io.FileInputStream;  
  3. import java.io.InputStream;  
  4. import java.net.URLDecoder;  
  5. import java.text.SimpleDateFormat;  
  6. import java.util.*;  
  7.   
  8. /** 
  9.  * Created by zhouhs on 2017/1/10. 
  10.  */  
  11. @SuppressWarnings("serial")  
  12. public class WordAction {  
  13.   
  14.     private String filePath; //文件路径  
  15.     private String fileName; //文件名称  
  16.     private String fileOnlyName; //文件唯一名称  
  17.   
  18.   
  19.     public String createWord() {  
  20.         /** 用于组装word页面需要的数据 */  
  21.         Map<String, Object> dataMap = new HashMap<String, Object>();  
  22.   
  23.         /** 组装数据 */  
  24.         dataMap.put("userName""seawater");  
  25.   
  26.         SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");  
  27.         dataMap.put("date", sdf.format(new Date()));  
  28.   
  29.         dataMap.put("content""freeMark生成Word文档段落内容");  
  30.   
  31.         List<Map<String, Object>> listInfo = new ArrayList<Map<String, Object>>();  
  32.         for (int i = 1; i <= 10; i++) {  
  33.             Map<String, Object> map = new HashMap<String, Object>();  
  34.             map.put("title""标题" + i);  
  35.             map.put("content""内容" + i);  
  36.             map.put("author""作者" + i);  
  37.             listInfo.add(map);  
  38.         }  
  39.         dataMap.put("listInfo", listInfo);  
  40.   
  41.         /** 文件名称,唯一字符串 */  
  42.         Random r = new Random();  
  43.         SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd");  
  44.         StringBuffer sb = new StringBuffer();  
  45.         sb.append(sdf1.format(new Date()));  
  46.         sb.append("_");  
  47.         sb.append(r.nextInt(100));  
  48.   
  49.         //文件路径  
  50.         filePath = "D:/doc_f/";  
  51.   
  52.         //文件唯一名称  
  53.         fileOnlyName = "用freemarker生成Word文档_" + sb + ".doc";  
  54.   
  55.         //文件名称  
  56.         fileName = "用freemarker生成Word文档.doc";  
  57.   
  58.         /** 生成word */  
  59.         WordUtil.createWord(dataMap, "freeMark.ftl", filePath, fileOnlyName);  
  60.   
  61.         return "createWordSuccess";  
  62.     }  
  63.   
  64.   
  65.     /** 
  66.      * 
  67.      * 下载生成的word文档 
  68.      */  
  69.     public String dowloadWord() {  
  70.         /** 先判断文件是否已生成  */  
  71.         try {  
  72.             //解决中文乱码  
  73.             filePath = URLDecoder.decode(filePath, "UTF-8");  
  74.             fileOnlyName = URLDecoder.decode(fileOnlyName, "UTF-8");  
  75.             fileName = URLDecoder.decode(fileName, "UTF-8");  
  76.   
  77.             //如果文件不存在,则会跳入异常,然后可以进行异常处理  
  78.             new FileInputStream(filePath + File.separator + fileOnlyName);  
  79.         } catch (Exception e) {  
  80.             e.printStackTrace();  
  81.             return "error";  
  82.         }  
  83.         return "dowloadWord";  
  84.     }  
  85.   
  86.     /** 
  87.      * 返回最终生成的word文档 文件流 
  88.      * 下载生成的word文档 
  89.      */  
  90.     public InputStream getWordFile() {  
  91.         try {  
  92.             //解决中文乱码  
  93.             fileName = URLDecoder.decode(fileName, "UTF-8");  
  94.   
  95.             /** 返回最终生成的word文件流  */  
  96.             return new FileInputStream(filePath + File.separator + fileOnlyName);  
  97.         } catch (Exception e) {  
  98.             e.printStackTrace();  
  99.             return null;  
  100.         }  
  101.     }  
  102.   
  103.   
  104.     public String getFilePath() {  
  105.         return filePath;  
  106.     }  
  107.   
  108.   
  109.     public void setFilePath(String filePath) {  
  110.         this.filePath = filePath;  
  111.     }  
  112.   
  113.   
  114.     public String getFileName() {  
  115.         return fileName;  
  116.     }  
  117.   
  118.   
  119.     public void setFileName(String fileName) {  
  120.         this.fileName = fileName;  
  121.     }  
  122.   
  123.   
  124.     public String getFileOnlyName() {  
  125.         return fileOnlyName;  
  126.     }  
  127.   
  128.   
  129.     public void setFileOnlyName(String fileOnlyName) {  
  130.         this.fileOnlyName = fileOnlyName;  
  131.     }  
  132. }  
工具类:

[java]  view plain  copy
  1. import freemarker.template.Configuration;  
  2. import freemarker.template.Template;  
  3.   
  4. import java.io.*;  
  5. import java.util.Map;  
  6.   
  7. public class WordUtil {  
  8.   
  9.     /** 
  10.      * 生成word文件 
  11.      * @param dataMap word中需要展示的动态数据,用map集合来保存 
  12.      * @param templateName word模板名称,例如:test.ftl 
  13.      * @param filePath 文件生成的目标路径,例如:D:/wordFile/ 
  14.      * @param fileName 生成的文件名称,例如:test.doc 
  15.      */  
  16.     @SuppressWarnings("unchecked")  
  17.     public static void createWord(Map dataMap,String templateName,String filePath,String fileName){  
  18.         try {  
  19.             //创建配置实例  
  20.             Configuration configuration = new Configuration();  
  21.   
  22.             //设置编码  
  23.             configuration.setDefaultEncoding("UTF-8");  
  24.   
  25.             //ftl模板文件  
  26.             configuration.setClassForTemplateLoading(WordUtil.class,"/");  
  27.   
  28.             //获取模板  
  29.             Template template = configuration.getTemplate(templateName);  
  30.   
  31.             //输出文件  
  32.             File outFile = new File(filePath+File.separator+fileName);  
  33.   
  34.             //如果输出目标文件夹不存在,则创建  
  35.             if (!outFile.getParentFile().exists()){  
  36.                 outFile.getParentFile().mkdirs();  
  37.             }  
  38.   
  39.             //将模板和数据模型合并生成文件  
  40.             Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"UTF-8"));  
  41.   
  42.   
  43.             //生成文件  
  44.             template.process(dataMap, out);  
  45.   
  46.             //关闭流  
  47.             out.flush();  
  48.             out.close();  
  49.         } catch (Exception e) {  
  50.             e.printStackTrace();  
  51.         }  
  52.     }  
  53. }  
访问方式就根据自己的需求去访问。

生成的文档如下:

word-n

word-c

到这里我们在Spring boot中使用freeMarker生成word文档就完成了。

猜你喜欢

转载自blog.csdn.net/qq_35192741/article/details/80757246