Freemaker实现导出word

第一步:打开导入模板,加入占位符及添加图片占位

如图:

第二步:模板另存为xml格式;打开xml代码,修改关键位置的数据;主要是根据xml模板修改占位符${a.itemi},去掉其中多出来的部分。

修改后数据如图:

            

 list遍历循环输出的话要在每一行前后加上<#list 你的数据list as 转换的变量名></#list>,相当于前段li标签的遍历循环输出一样,找到循环的行,加上这个list就行了

如图:

      

 图片的话,在模板里面先加入图片占位,打开xml文档,图片所在的位置会有一大串base64编码,将图片形成的一大串base64编码改成图片的数据变量,如${image}

如图:  

       

/**

*service层

**/

public ResponseFile exportWord(ServiceRequest request, int id) thorws Exception;

/**

*impl层

**/

public ResponseFile exportWord(ServiceRequest request, int id) thorws Exception{

  YoungInfoQuery voById = youngInfo.getVOById(id);

  //准备数据

  Map dataMap = new HashMap();

  dataMap.put("lastMonth",voById.getTitle() != null ? voById.getTitle() : "");

  dataMap.put("item1",voById.getTiaoMu1() != null ? voById.getTiaoMu1() : "");

  dataMap.put("item2",voById.getTiaoMu2() != null ? voById.getTiaoMu2() : "");

  dataMap.put("item3",voById.getTiaoMu3() != null ? voById.getTiaoMu3() : "");

  dataMap.put("item4",voById.getTiaoMu4() != null ? voById.getTiaoMu4() : "");

  dataMap.put("item5",voById.getTiaoMu5() != null ? voById.getTiaoMu5() : "");

  dataMap.put("item6",voById.getTiaoMu6() != null ? voById.getTiaoMu6() : "");

  String  oapath =  System.getProperty("oapath");

  Template t = null;

  String templateFilePath = oapath + xxx.ftl; //存放ftl文件的位置

  Configuration configuration = new Configuration();

  configuration.setDefaultEncoding("UTF-8")

  try {

    String ftlPath = templateFilePath.substring(0,templateFilePath.lastIndexof("/"));//ftl文件位置

    configuration.setDirectoryForTemplateLoading(new File(ftlPath));//加载文件

    String ftlFile = templateFilePath.substring(templateFilePath.lastIndexof("/")+1);//ftl文件

    String targetFile = oapath+voById.getTitle()+".doc";

    File outFile = new File(targetFile)://指定输出word的路径

    if(!outFile.exists(){

      outFile.createNewFile();

    }

    String fileName = outFile.getName();

    Writer out = null;

    out new BufferedWriter (new OutputStreamWriter(new FileOutputStream(outFile),"utf-8"),10240);

    t.process(dataMap,out);

    return new ResponseFile(fileName,new FileInputStream(outFile),outFile.length(),outFile.lastModifie()):

  } catch (Exception e) {

    e.printStacTrace():

  }

}

猜你喜欢

转载自www.cnblogs.com/bwl914/p/12362088.html