根据模板自动生成word文件
介绍:
有一个很简易的工具能够替换word模板中的一些文字,生成新文件。
这个工具就是freemaker,先百度一下下个jar包。
具体使用:
-
要替换的部分用${}包裹起来;
-
将word文件另存为xml;
-
将此xml文件的后缀名改为ftl;
-
具体替换代码如下:
package com.test; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.util.HashMap; import java.util.Map; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; public class Test { public static void main(String[] args) { // 需要一个map来存放替换模板的值 Map<String, Object> dataMap = new HashMap<String, Object>(); // map的键名与模板中的一一对应 dataMap.put("title", "这是一个自动生成的标题"); Configuration configuration = new Configuration(); configuration.setDefaultEncoding("utf-8"); Writer out = null; Template template = null; try { // 新建文件 File outFile = new File("C:\\Users\\15872\\Desktop\\test.doc"); out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"), 10240); // 读取模板所在目录 configuration.setDirectoryForTemplateLoading(new File("C:\\Users\\15872\\Desktop")); // 读取模板 template = configuration.getTemplate("test.ftl", "utf-8"); // 替换 template.process(dataMap, out); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (TemplateException e) { e.printStackTrace(); } finally { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } }
效果如下: