java freemarker模板 实现word文件导出

来源:互联网 发布:如何找回淘宝账号 编辑:程序博客网 时间:2024/05/17 11:05

使用freemarker模板化导出word文件 java代码实现

因为是word文档模板所以先弄一个简单的模板这里我用了一个word表格作为演示导出例子,如图word模板是这样的:
这里写图片描述


计划导出一个5*4的表格。

首先将这个doc文档另存为xml的文件,用notepad++打开xml文件如下图:
这里写图片描述
需要将将包含01,02,03,04 这些数据的格式以及包含这个格式的标签做改成freemarker的格式和遍历list,改完后如下图:
这里写图片描述


将改完格式后的文件保存为template.ftl文件 放在和实现代码java文件相同目录下(也可以写相对路径)
然后开始写代码,模拟导出数据的过程。
需要一个freemarker jar包,这里写图片描述
可以去这里下载 http://search.maven.org/


demo

package cn.com.taiji.common;import java.io.BufferedWriter;import java.io.File;import java.io.FileOutputStream;import java.io.OutputStreamWriter;import java.io.UnsupportedEncodingException;import java.io.Writer;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import freemarker.template.Configuration;import freemarker.template.Template;/** * @date 2017年1月4日 * @author xie * freemarker 模板输出格式化word文件 */public class WordUtils {  public void createDoc(Map<String,Object> dataMap,String fileName) throws UnsupportedEncodingException {      //dataMap 要填入模本的数据文件      //设置模本装置方法和路径,FreeMarker支持多种模板装载方法。可以重servlet,classpath,数据库装载,      Configuration configuration = new Configuration();    configuration.setDefaultEncoding("utf-8");     configuration.setClassForTemplateLoading(this.getClass(),"");      Template t=null;      try {          //test.ftl为要装载的模板          t = configuration.getTemplate("template.ftl");          //输出文档路径及名称          File outFile = new File(fileName);          Writer out = null;          FileOutputStream fos=null;          fos = new FileOutputStream(outFile);          OutputStreamWriter oWriter = new OutputStreamWriter(fos,"UTF-8");          //这个地方对流的编码不可或缺,使用main()单独调用时,应该可以,但是如果是web请求导出时导出后word文档就会打不开,并且包XML文件错误。主要是编码格式不正确,无法解析。          //out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));           out = new BufferedWriter(oWriter);          t.process(dataMap, out);           out.close();           fos.close();      } catch (Exception e) {          e.printStackTrace();      }  }    public static void main(String[] args) {    Map<String, Object> dataMap = new HashMap<String, Object>();      List<Map<String, Object>> list1 = new ArrayList<Map<String, Object>>();    for (int i = 0; i < 5; i++) {        Map<String, Object> map = new HashMap<String, Object>();        map.put("c1", i+"1");        map.put("c2", i+"2");        map.put("c3", i+"3");        map.put("c4", i+"4");        list1.add(map);      }      dataMap.put("table1", list1);      WordUtils mdoc = new WordUtils();      try {      mdoc.createDoc(dataMap, "E:/outFile.doc");    } catch (Exception e) {      e.printStackTrace();    }  }}

导出后的文件是这样的

这里写图片描述

0 0
原创粉丝点击