JAVA 使用freemarker导出Word - 学习记录一

xu.wang

发布于 2019.12.17 21:57 阅读 2778 评论 0

     本文引用自:https://www.iteye.com/blog/18810098265-2056122
 
    当前项目需要按照格式生成word文件。由于生成的Word格式简单,所以百度搜寻了一下决定使用freemarker进行生成。因为使用freemarker比较生成比较简单,不像iReport 需要下载软件。

   本文主要记录简单模板的导出功能、不包含图片以及循环列表。

 

    第一步:创建Word文件,在需要替换文字的位置用占位符进行占位- ${}

    例如:   

        标题 : ${title}

        小组名称: ${groupName}

        小组信息: ${groupInfo}

   

第二步:  将word另存为xml格式。

 

  第三步:将另存为的xml文件直接改名为 *.ftl

   

第四步:敲代码

       在pom中加入以下依赖:

<!-- https://mvnrepository.com/artifact/org.freemarker/freemarker -->
    <dependency>
      <groupId>org.freemarker</groupId>
      <artifactId>freemarker</artifactId>
      <version>2.3.28</version>
    </dependency>

      下面使用Junit进行测试:(注意引入的包)

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.Version;
import org.junit.Test;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

public class WordTest {

    @Test
    public void test(){
        Map<String,Object> dataMap = new HashMap<String, Object>();
        try {
            //标题
            dataMap.put("title", "标题");
            //小组名称
            dataMap.put("groupName", new SimpleDateFormat("yyyy年MM月dd日").format(new SimpleDateFormat("yyyy-MM-dd").parse("2018-09-19")));
         
            //小组信息
            dataMap.put("groupInfo", "张三");

            //Configuration 用于读取ftl文件
            Configuration configuration = new Configuration(new Version("2.3.0"));
            configuration.setDefaultEncoding("utf-8");

            /**
             * 以下是两种指定ftl文件所在目录路径的方式,注意这两种方式都是
             * 指定ftl文件所在目录的路径,而不是ftl文件的路径
             */
            //指定路径的第一种方式(根据某个类的相对路径指定)
//                configuration.setClassForTemplateLoading(this.getClass(), "");

            //指定路径的第二种方式,我的路径是C:/a.ftl
            configuration.setDirectoryForTemplateLoading(new File("/Users/xuwang/Desktop/"));

            //输出文档路径及名称
            File outFile = new File("/Users/xuwang/Desktop/报销信息导出.doc");

            //以utf-8的编码读取ftl文件
            Template template = configuration.getTemplate("wordTemplate.ftl", "utf-8");
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"), 10240);
            template.process(dataMap, out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}

 

    第五步: 运行,结果如下