详细教程:springboot导出word之freemarker导出--------手动绘制模板方式导出(一)

本文介绍如何使用Maven安装Freemarker依赖,详细步骤包括绘制Word模板、转换为FTL格式,以及通过Java代码填充数据并生成Word文档。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.安装MAVEN依赖

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

2.绘制word模板

  • 打开word,按照需求绘制模板内容
  • 保存为xml格式
  • 手动更改保存后的文件格式为ftl
  • 放入idea目录下,格式化xml标签,去掉${}前后的空格

3.编写测试代码

    private Configuration configuration = null;    

    public ExportWordService() {
        configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");
    }

   public void createDoc() throws UnsupportedEncodingException {

        // 填充的数据
        Map<String,String> dataMap=new HashMap<>();
        dataMap.put("name", "张三");
        dataMap.put("age", "18");

        //这里我们的模板是放在templates包下面
        configuration.setClassForTemplateLoading(this.getClass(), "/templates");

        Template t=null;
        try {
            //test.ftl为要装载的模板
            t = configuration.getTemplate("test.ftl");
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 导出的文件名
        File outFile = new File("D:/outFilessa"+Math.random()*10000+".doc");
        Writer out = null;
        try {
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }

        try {
            // 执行生成word
            t.process(dataMap, out);
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

4.测试结果

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值