Springboot 集成freemark生成word

Springboot 集成freemark生成word

最近遇到一个业务 需要按照指定的模板填充数据 用到了freemark简单记录一下

制作模板

1首先把需要填充的模板,按照需要填充的数据,进行替换。在这里插入图片描述

2把模板另存为xml文件,然后放入idea,进行数据的格式化,方便替换。大多时间圈起来的部分是不在一起的,进行操作放在一起即可。然后修改文件后缀名为.ftl

在这里插入图片描述

引入freemark

引入依赖

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

wordUtils 工具类

public class WordUtil {
    private static final Logger logger = LoggerFactory.getLogger(WordUtil.class);

    private Template template;

    private final String path = "替换成自己的路径";

    /**
     * 初始化
     */
    public WordUtil(String templateName) throws Exception {
        System.out.println("path = " + path);
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_20);
        configuration.setDirectoryForTemplateLoading(new File(path));
        configuration.setOutputEncoding("utf-8");
        template = configuration.getTemplate(templateName);
    }

  
    /**
     * 导出到浏览器
     */
    public void doExports(String fileName, Map<String, Object> results,
                          HttpServletResponse response) throws TemplateException, IOException {
        StringWriter out = new StringWriter();
        Writer writer = new BufferedWriter(out, 10240);
        template.process(results, writer);
        InputStream fin = new ByteArrayResource(out.toString().getBytes(StandardCharsets.UTF_8)).getInputStream();
        ServletOutputStream outputStream;
        response.setCharacterEncoding("utf-8");
        response.setContentType("Content-Type;application/json");
        response.setHeader("Content-Disposition", "attachment;filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"");
        outputStream = response.getOutputStream();
        // 缓冲区
        byte[] buffer = new byte[1024];
        int bytesToRead;
        // 通过循环将读入的Word文件的内容输出到浏览器中
        while ((bytesToRead = fin.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesToRead);
        }
        if (outputStream != null) {
            outputStream.close();
        }
        fin.close();
    }

wordService 主要进行数据填充

@Override
    public Map<String, Object> assembleData(OracleInfMer oracleInfMer, OracleTermBase oracleTermBase) {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        //组装模板需要的数据
        //1年月日
        Calendar calendar = Calendar.getInstance();
        dataMap.put("year", calendar.get(Calendar.YEAR));
        dataMap.put("month", calendar.get(Calendar.MONTH) + 1);
        dataMap.put("day", calendar.get(Calendar.DAY_OF_MONTH));
        //商户号
        dataMap.put("cusid", oracleTermBase.getCusid());
        //终端号
        dataMap.put("termno", oracleTermBase.getTermno());
        //机身号
        dataMap.put("sequence", oracleTermBase.getSequence());
        //工商名
        dataMap.put("cusname", oracleInfMer.getCUSNAME());
        //营业名称
        dataMap.put("branchname", oracleTermBase.getBranchname());
        //签购单
        dataMap.put("branchname", oracleTermBase.getBranchname());
        //终端类型
        dataMap.put("termtype", oracleTermBase.getTermtype());
        //押金
        if (StringUtils.isEmpty(oracleTermBase.getGuaranty())) {
            dataMap.put("guaranty", 0);
        } else {
            dataMap.put("guaranty", oracleTermBase.getGuaranty());
        }
        //安装地址
        dataMap.put("branchaddr", oracleTermBase.getBranchaddr());
        //联系人以及电话
        dataMap.put("contacter", oracleTermBase.getContacter());
        dataMap.put("contacttel", oracleTermBase.getContacttel());
        //拓展人
        dataMap.put("devlman", oracleInfMer.getDEVLMAN());
        return dataMap;
    }

controller控制器层

Map<String, Object> dataMap = oracleInfMerService.assembleData(oracleInfMer, oracleTermBase);
        String fileName = "终端号" + oracleTermBase.getTermno() + ".doc";
        WordUtil wordUtil = new WordUtil("word.ftl");
        wordUtil.doExports(fileName, dataMap, response);

集成freemark相对简单,就是简单的数据填充,很好理解,制作模板的时候会稍微有点麻烦,会出错,细心一点就好。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SpringBoot_Freemarker生成Word_多个表格+两层嵌套循环; 步骤说明: 1.用Microsoft Office Word打开word原件;将文档中需要动态生成的内容,替换为属性名 ${name} 2.另存为,选择保存类型Word 2003 XML 文档(*.xml) 3.用Firstobject free XML editor打开文件,选择Tools下的Indent【或者按快捷键F8】格式化文件内容。左边是文档结构,右边是文档内容; 4. 文档生成后有时需要手动修改,查找第一步中设置的属性名,可能会产生类似${n.....ame}类似的样子,我们将将名字中间的标签删掉,恢复为${name} 5. word模板中有表格,需要循环的位置, 用 标签将第二对 标签(即除表头的w:tr标签后的一对)包围起来 同时表格内的属性例如${name},在这里需要修改为${user.name} (userList是集合在dataMap中的key, user是集合中的每个元素, 类似), 如图: PLUS:若表格之外还有嵌套的循环,也需要用,注意这里的标签不要和某对其他标签交叉,不可以出现这种 6. 标识替换完之后,另存为.ftl后缀文件即可。 代码里是相对有一丢丢复杂的,两层嵌套循环; 总(dataMap) deptName 部门名 list(Table)表的集合 table1(map) table-名字 ${map.table} tableName-中文名 ${map.tableName} columnCount-字段数 ${map.columnCount} recordCount-记录数 ${map.recordCount} listA-List--表格1 map.listA column Model属性——字段名 ${model.column} columnName Model属性——字段中文名 ${model.column} rate Model属性——字段占比 ${model.rate} nullValueCount Model属性——字段空值数 ${model.nullValueCount} listB-List--表格2 map.listB …… listC-List--表格3 map.listC …… table2 table-名字 ${map.table} tableName-中文名 ${map.tableName} columnCount-字段数 ${map.columnCount} recordCount-记录数 ${map.recordCount} listA-List--表格1 map.listA column Model属性——字段名 ${model.column} columnName Model属性——字段中文名 ${model.column} rate Model属性——字段占比 ${model.rate} nullValueCount Model属性——字段空值数 ${model.nullValueCount} listB-List--表格2 map.listB …… listC-List--表格3 map.listC …… table3 ……

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值