使用freeMarker生成word文档(初级入门)

最近要生成word文档,就学习了一下。

添加maven依赖

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

1、在word模板中定义好占位符${}形式,另存为.xml格式,然后重命名为.ftl格式

2、将test.ftl放入相应文件夹下

(1)工具类

import freemarker.template.Configuration;
import freemarker.template.Template;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public class ExportDocFreeMarker {
    private Configuration configuration;
    private String encoding;


    public ExportDocFreeMarker(String encoding) {
        this.encoding = encoding;
        configuration = new Configuration(Configuration.VERSION_2_3_22);
        configuration.setDefaultEncoding(encoding);
        //configuration.setClassForTemplateLoading(this.getClass(), "/com/cars/bjcyqs/util/print");
        try {
       //模板所在文件路径,Freemarker提供了3种加载模板目录的方法,此处用的是基于文件系统
            configuration.setDirectoryForTemplateLoading(new File("E:/bjcyqs/bjcyqs/bjcyqs-web/target/bjcyqs-web/file"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public Template getTemplate(String name) throws Exception {
        return configuration.getTemplate(name);
    }

    public String getImageStr(String image) throws IOException {
        InputStream is = new FileInputStream(image);
        BASE64Encoder encoder = new BASE64Encoder();
        byte[] data = new byte[is.available()];
        is.read(data); is.close();
        return encoder.encode(data);
    }

    public Map<String, Object> getDataMap() {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("bj0","中华人民共和国首都");
        dataMap.put("bj1","政治中心");
        dataMap.put("bj2","天津");
        dataMap.put("bj3","河北");
        dataMap.put("bj4","永定河、潮白河、北运河、拒马河");
        dataMap.put("bj5","2154.2");
        dataMap.put("bj6","30320");
        dataMap.put("bj7","14");
        /*try {
            dataMap.put("image", getImageStr("D:\\头像.jpg"));
        } catch (IOException e) {
            e.printStackTrace();
        }*/
        return dataMap;
    }

    public void exportDoc(HttpServletResponse response,String name, String doc) throws Exception {
        //将模板和数据合并成文件
        Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(doc), encoding));
        try {
            //生成文件
            getTemplate(name).process(getDataMap(), writer);
            writer.flush();
            InputStream input = null;
            OutputStream outputString = null;
            try {
                response.setHeader("Content-Disposition","attachment; filename=" + URLEncoder.encode( "测试文件.doc", "UTF-8"));//直接下载doc文档
                input = new BufferedInputStream(new FileInputStream(new File(doc)));
                outputString = new BufferedOutputStream(response.getOutputStream());
                EchartPdfUtil.copy(input, outputString);
                outputString.flush();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }catch (IOException e) {
                e.printStackTrace();
            }finally{
                try {
                    input.close();
                    outputString.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (null != writer) {
                writer.close();
            }
        }

    }

    public static void main(String[] args) throws Exception {
        ExportDocFreeMarker maker = new ExportDocFreeMarker("UTF-8");
        //maker.exportDoc("D:\\test.doc", "test.ftl");
    }

(2)控制类

@RequestMapping("/exportDoc")
    public void exportPdf(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ExportDocFreeMarker maker = new ExportDocFreeMarker("UTF-8");
        try {
            maker.exportDoc(response,"testFreeMarker.ftl","D:/test.doc");//在D盘生成文件
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

(3)生成的文档

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值