<!--添加freeMarker--> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.20</version> </dependency>
下一步咱们要作的是先好咱们的word模板而后将模板转换为xml文件。在word模板中须要定义好咱们的占位符哦,使用${string}的方式。“string”根据本身的爱好定义就行了。java
过程以下:程序员
word文档:数据库
而后将咱们的word文档另存为xml文档。编程
将咱们的xml文档的后缀改成ftl,而后用能够打开ftl文件的软件打开咱们的ftl文件。在这里咱们有几个须要注意的地方。编程语言
第一,定义的占位符可能会被分开了。就像下面这样:工具
咱们须要作的就是删掉多余的部分,图中我定义的是${userName}.因此我就把多余的删掉,变成${userName}就能够了。编码
第二,咱们须要注意的就是在咱们的表格部分须要本身添加freeMarker标签。在表格代码间用自定的标签括起来。定义的参数要和咱们在方法中定义的一致,不然没法取到值。spa
表格开始:code
结束:</list>orm
package czc.sup.system.model.six; 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(); } } }
public static void main(String[] args) { /** 用于组装word页面须要的数据 */ Map<String, Object> dataMap = new HashMap<String, Object>(); DataWord dataWord = new DataWord("model", "name", "designCode", "code", "met", "date", "temp", "humi", "hly"); List<Object> datas = new ArrayList<>(); for(int i=0;i<10;i++){ Data data = new Data("1","检测名"+i, "norm", "result", "remark"); datas.add(data); } dataMap.put("product",dataWord); dataMap.put("datas",datas); String filePath = ""; if (IsWhatSystem.whatSystem()) { //文件路径 filePath = "D:/doc_f/"; }else { filePath = "/doc_f/"; } //文件惟一名称 String fileOnlyName = "生成Word文档.doc"; /** 生成word 数据包装,模板名,文件生成路径,生成的文件名*/ WordUtil.createWord(dataMap, "quality.ftl", filePath, fileOnlyName); }
而后就在相应的目录下导出word文档了