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

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.测试结果

发布了65 篇原创文章 · 获赞 66 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_44096448/article/details/104993438
今日推荐