java根据模板导出word

java根据模板导出word

日常开发中,常常会遇到各种各样的表格进行导出,比较好的办法就是提前弄好word模版,再通过遍历的方式进行导出文档

1、制作word模版

模版编写 内容替换

目标下面模版进行多页展示

将word转换成xml

将xml格式化 再将xml改成ftl

xml格式化地址

list找到起始位置和结束位置

起始位置插入<#list list as l>

结束位置插入</#list>

2、java代码

pom 复制代码
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.28</version>
        </dependency>

ExportWordFtl.java

java 复制代码
package com.liuhm.utils;

import freemarker.template.Configuration;
import freemarker.template.Template;
import org.junit.platform.commons.util.StringUtils;

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

/**
 *  
 *  @ClassName:ExportWordFtl
 *  @Description: TODO
 *  @Author: liuhaomin
 *  @Date: 2023/7/21 16:02
 */
public class ExportWordFtl {
    /**
     * 生成word文件
     * @param dataMap word中需要展示的动态数据,用map集合来保存
     * @param templateName word模板名称,例如:test.ftl
     * @param filePath 文件生成的目标路径,例如:D:/wordFile/
     * @param fileName 生成的文件名称,例如:test.doc
     */
    @SuppressWarnings("unchecked")
    public static File createWord(Map dataMap, String templateName, String filePath, String fileName){
        try {
            //创建配置实例
            Configuration configuration = new Configuration();
            //设置编码
            configuration.setDefaultEncoding("UTF-8");

            //ftl模板文件
            configuration.setClassForTemplateLoading(ExportWordFtl.class,"/");

            //获取模板
            Template template = configuration.getTemplate(templateName);

            //输出文件
            File outFile ;
            if(StringUtils.isBlank(filePath)){
                outFile = new File(fileName);
            }else {
                outFile = new File(filePath+ File.separator+fileName);
                //如果输出目标文件夹不存在,则创建
                if (!outFile.getParentFile().exists()){
                    outFile.getParentFile().mkdirs();
                }
            }

            //将模板和数据模型合并生成文件
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"UTF-8"));

            //生成文件
            template.process(dataMap, out);

            //关闭流
            out.flush();
            out.close();
            return outFile;
        } catch (Exception e) {
            e.printStackTrace();

        }
        return null;
    }
    public static void main(String[] args) {
        List<Map<String, Object>> list = new ArrayList<>();
        for (int i = 0; i <10 ; i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("datasubmit_updated_time","2023-07-02 12:12:12");
            Date date = new Date();
            map.put("nyliq",date);
            map.put("yhorq","单位名称"+i);
            map.put("xiikv","隐患类型"+i);
            map.put("kuzjg","隐患整改通知书类型"+i);
            map.put("hnvld","隐患详情"+i);
            map.put("gnbcv",date);
            map.put("malio",date);
            map.put("skpfm","整改情况告知书编号"+i);
            map.put("vgnje","整改状态"+i);
            map.put("vutap","备注"+i);
            list.add(map);
        }
        Map<String,Object> dataMap = new HashMap<String, Object>();
        dataMap.put("list", list);

        try {
            String path = "C:\\Users\\Administrator\\Desktop\\";
//            path = URLDecoder.decode(Test.class.getClassLoader().getResource("").getPath(), "UTF8");
            File file = ExportWordFtl.createWord(dataMap, "template/demo.ftl", path, "demo-t.doc");
            System.out.println("文档生成成功,路径为" + file.getAbsolutePath() );
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

测试

执行main方法

生成文件

所有的文件格式正确

博客地址

代码下载

下面的export-template-word

相关推荐
麦兜*1 分钟前
【Spring Boot】Spring Boot 4.0 的颠覆性AI特性全景解析,结合智能编码实战案例、底层架构革新及Prompt工程手册
java·人工智能·spring boot·后端·spring·架构
野犬寒鸦9 分钟前
MyBatis-Plus 中使用 Wrapper 自定义 SQL
java·数据库·后端·sql·mybatis
future141210 分钟前
项目开发日记
前端·学习·c#·游戏开发
expect7g17 分钟前
Java的DNS缓存问题
java·后端
oioihoii17 分钟前
C++11中的std::minmax与std::minmax_element:原理解析与实战
java·开发语言·c++
karry013041 分钟前
高并发导致重复key问题--org.springframework.dao.DuplicateKeyException
java·数据库·ide
全栈凯哥43 分钟前
20.缓存问题与解决方案详解教程
java·spring boot·redis·后端·缓存
小莫分享1 小时前
2023年最新总结,阿里,腾讯,百度,美团,头条等技术面试题目,以及答案,专家出题人分析汇总。
java·后端·面试·职场和发展
Brookty1 小时前
【操作系统】线程
java·linux·服务器·后端·学习·java-ee·操作系统
Dovis(誓平步青云)1 小时前
探索飞算 JavaAI 进阶:解锁高效Java开发的新维度
java·开发语言·飞算java