最近项目中需要根据模板生成word文档,模板文件也是word文档。当时思考一下想用POI API来做,但是觉得用起来相对复杂。后来又找了一种方式,使用freemarker模板生成word文件,经过尝试觉得还是相对简单易行的。

使用freemarker模板生成word文档主要有这么几个步骤

1、创建word模板:因为我项目中用到的模板本身是word,所以我就直接编辑word文档转成freemarker(.ftl)格式的。

 Java 根据模板动态生成word文件

2、将改word文件另存为xml格式,注意使用另存为,不是直接修改扩展名。

3、将xml文件的扩展名改为ftl

4、编写java代码完成导出

使用到的jarfreemarker.jar (2.3.28) ,其中Configuration对象不推荐直接new Configuration(),仔细看Configuration.class文件会发现,推荐的是 Configuration(Version incompatibleImprovements) 这个构造方法,具体这个构造方法里面传的就是Version版本类,而且版本号不能低于2.3.0

闲言碎语不再讲,直接上代码

 1 public static void exportDoc() {
 2         String picturePath = "D:/image.png";
 3         Map<String, Object> dataMap = new HashMap<String, Object>();
 4         dataMap.put("brand", "海尔");
 5         dataMap.put("store_name", "海尔天津");
 6         dataMap.put("user_name", "小明");
 7 
 8         //经过编码后的图片路径
 9         String image = getWatermarkImage(picturePath);
10         dataMap.put("image", image);
11 
12         //Configuration用于读取ftl文件
13         Configuration configuration = new Configuration(new Version("2.3.0"));
14         configuration.setDefaultEncoding("utf-8");
15 
16         Writer out = null;
17         try {
18             //输出文档路径及名称
19             File outFile = new File("D:/导出优惠证明.doc");
20             out = new BufferedWriter(new OutputStreamWriter(new 
21             FileOutputStream(new File("outFile")), "utf-8"), 10240);
22         } catch (UnsupportedEncodingException e) {
23             e.printStackTrace();
24         } catch (FileNotFoundException e) {
25             e.printStackTrace();
26         }
27         // 加载文档模板
28         Template template = null;
29         try {
30             //指定路径,例如C:/a.ftl 注意:此处指定ftl文件所在目录的路径,而不是ftl文件的路径
31             configuration.setDirectoryForTemplateLoading(new File("C:/"));
32             //以utf-8的编码格式读取文件
33             template = configuration.getTemplate("导出优惠证明.ftl", "utf-8");
34         } catch (IOException e) {
35             e.printStackTrace();
36             throw new RuntimeException("文件模板加载失败!", e);
37         }
38 
39         // 填充数据
40         try {
41             template.process(dataMap, out);
42         } catch (TemplateException e) {
43             e.printStackTrace();
44             throw new RuntimeException("模板数据填充异常!", e);
45         } catch (IOException e) {
46             e.printStackTrace();
47             throw new RuntimeException("模板数据填充异常!", e);
48         } finally {
49             if (null != out) {
50                 try {
51                     out.close();
52                 } catch (IOException e) {
53                     e.printStackTrace();
54                     throw new RuntimeException("文件输出流关闭异常!", e);
55                 }
56             }
57         }
58     }
View Code

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-03-03
  • 2022-12-23
  • 2021-04-29
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-05-18
  • 2022-02-02
相关资源
相似解决方案