Java使用FreeMarker自动生成Word文档

背景:根据模板填充导出word

一.添加依赖

1 <dependency>
2      <groupId>org.freemarker</groupId>
3      <artifactId>freemarker</artifactId>
4      <version>2.3.20</version>
5 </dependency>

二.定义word模板

在这里插入图片描述

三.将生成的word另存为xml格式

在这里插入图片描述

四.修改内容

1.将对应的内容填写成${}的形式
在这里插入图片描述
2.针对列表循环的内容,需要加list标签,如下图所示
在这里插入图片描述
这些全部弄好之后,模板就制作完了,修改文件为.ftl即可,然后把模板放入到项目中。

五.编写代码

package com.sinosoft.springbootplus.demandConfirm.application.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sinosoft.springbootplus.schedule.service.JwPtkScheduleCourseDetailByClassIdApiService;
import com.sinosoft.springbootplus.schedule.vo.JwPtkScheduleCourseDetailByClassId;
import com.sinosoft.springbootplus.util.UUIDUtil;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

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


/**
 * <pre>
 * 后勤需求确认单导出 服务实现类
 * </pre>
 *
 * @author 李佳锴
 * @since 2021-12-29
 */

@Service
@Slf4j
public class HqDemandConfirmExportServiceImpl extends BaseServiceImpl<HqDemandConfirmMapper, HqDemandConfirm> implements HqDemandConfirmExportService {
    private static final String ENCODING = "UTF-8";
    private static Configuration cfg = new Configuration();

    //初始化cfg
    static {
        //设置模板所在文件夹
        cfg.setClassForTemplateLoading(HqDemandConfirmExportServiceImpl.class, "/templates");
        // setEncoding这个方法一定要设置国家及其编码,不然在ftl中的中文在生成html后会变成乱码
        cfg.setEncoding(Locale.getDefault(), ENCODING);
        // 设置对象的包装器
        cfg.setObjectWrapper(new DefaultObjectWrapper());
        // 设置异常处理器,这样的话就可以${a.b.c.d}即使没有属性也不会出错
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);

    }

    //获取模板对象
    public static Template getTemplate(String templateFileName) throws IOException {
        return cfg.getTemplate(templateFileName, ENCODING);
    }

    /**
     * 据数据及模板生成文件
     * @param data             Map的数据结果集
     * @param templateFileName ftl模版文件名
     * @param outFilePath      生成文件名称(可带路径)
     */
    public static File crateFile(Map<String, Object> data, String templateFileName, String outFilePath) {
        Writer out = null;
        File outFile = new File(outFilePath);
        try {
            // 获取模板,并设置编码方式,这个编码必须要与页面中的编码格式一致
            Template template = getTemplate(templateFileName);
            if (!outFile.getParentFile().exists()) {
                outFile.getParentFile().mkdirs();
            }
            out = new OutputStreamWriter(new FileOutputStream(outFile), ENCODING);
            // 处理模版
            template.process(data, out);
            out.flush();
            log.info("由模板文件" + templateFileName + "生成" + outFilePath + "成功.");
        } catch (Exception e) {
            log.error("由模板文件" + templateFileName + "生成" + outFilePath + "出错");
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                log.error("关闭Write对象出错", e);
                e.printStackTrace();
            }
        }
        return outFile;
    }



    @Override
    public void getHqDemandConfirmPageList(Long confirmId) throws Exception {

        //用于存储所有数据
        Map<String,Object> data = new HashMap<>();

        //查询基本信息
            data.put("checkOutStartDate",checkOutStartDate);
            data.put("checkOutEndDate",checkOutEndDate);
            data.put("teachAssistant",baseInfo.getTeachAssistant());
            data.put("phone",hqDemandConfirms.getPhone());


        //获取场地所有信息
        List<HqDemandConfirm> hqDemandConfirmExport = hqDemandConfirmMapper.getHqDemandConfirmExport(queryWrapperDemandConfirms);
        //获取培训单所有班级Id
        List<Long> list = new ArrayList<>();
        for (HqDemandConfirm demandConfirm : hqDemandConfirmExport) {
            list.add(demandConfirm.getClassId());
        }
        //用于存储遍历出来的所有数据
        List<Map<String, Object>> scheduleCourseDetailMaps = new ArrayList<>();
        for (Long aLong : list) {

            List<JwPtkScheduleCourseDetailByClassId> jwPtkScheduleCourseDetailByClassId = jwPtkScheduleCourseDetailByClassIdApiService.getJwPtkScheduleCourseDetailByClassId(aLong);
            for (JwPtkScheduleCourseDetailByClassId ptkScheduleCourseDetailByClassId : jwPtkScheduleCourseDetailByClassId) {
                //   list2.add(ptkScheduleCourseDetailByClassId);
                //根据班级Id获取场地所有信息
                Map<String,Object> scheduleCourseDetail = new HashMap<>();
                String courseDate = sdf2.format(ptkScheduleCourseDetailByClassId.getCourseDate());
                scheduleCourseDetail.put("courseDate",courseDate);
                scheduleCourseDetail.put("courseBeginTime",ptkScheduleCourseDetailByClassId.getCourseBeginTime());
                scheduleCourseDetail.put("courseEndTime",ptkScheduleCourseDetailByClassId.getCourseEndTime());
                scheduleCourseDetail.put("classroom",ptkScheduleCourseDetailByClassId.getClassroom());
                /* scheduleCourseDetail.put("trueNum",ptkScheduleCourseDetailByClassId.getTrueNum());*/
                scheduleCourseDetail.put("remark",ptkScheduleCourseDetailByClassId.getRemark());

                scheduleCourseDetailMaps.add(scheduleCourseDetail);
            }
        }




        //用于存储遍历出来的所有数据
        List<Map<String, Object>> detailMaps = new ArrayList<>();
        //房间使用情况导入
        for (HqDormUseInfo hqDormUseInfo : roomInfos) {
            //存储遍历出来的一条数据
            Map<String,Object> dormUseInfo = new HashMap<>();
            if (hqDormUseInfo.getDormType() == 0){
                dormUseInfo.put("dormType","单间");
            }else if (hqDormUseInfo.getDormType() == 1){
                dormUseInfo.put("dormType","标间");
            }else {
                dormUseInfo.put("dormType","套间");
            }
            dormUseInfo.put("dormNum",hqDormUseInfo.getDormNum());
            dormUseInfo.put("remarks",hqDormUseInfo.getRemarks());
            detailMaps.add(dormUseInfo);
        }

      
        //将房间信息存储到总集合中
        data.put("detailMaps",detailMaps);
        //将用餐情况存储到总集合中
        data.put("detailMealMaps",detailMealMaps);
        //将住宿情况其他要求存储到总集合中
        data.put("accommodationRequirements",hqDemandConfirms.getAccommodationRequirements());
        //将场地使用其他要求存储到总集合中
        data.put("uenueRequirements",hqDemandConfirms.getUenueRequirements());
        //将用餐情况其他要求存储到总集合中
        data.put("mealRequirements",hqDemandConfirms.getMealRequirements());
        //将特殊情况存储到总集合中
        data.put("hqConfirmExplain",hqConfirmExplain.getExplainS());
        //将场地使用存储到总集合中
        data.put("scheduleCourseDetailMaps",scheduleCourseDetailMaps);
        //将联系人存储到总集合中
        data.put("userName",hqDemandConfirms.getUserName());
        //将邮箱存储到总集合中
        data.put("email",hqDemandConfirms.getEmail());
        //存储路径
        crateFile(data, "后勤保障需求单2.ftl", "D:/后勤保障需求单"+ UUIDUtil.getUUID() +".doc");

    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值