项目中使用freeMarker创建自定义表单

自定义模板

修改xml变成ftl格式 ,将ftl格式文件放入templates下,用idea打开在ctrl +A 然后ctrl +alt+L格式化

 

 

 

 

折叠起来看到有多个pkg

主要是修改document.xml这个pkg

自定义文字模板

 

自定义表格

 

改变为

 

自定义图片的模板

 

编码

@ApiOperation(value = "导出方式三", notes = "导出文件")
    @PostMapping("/exportMThree")
    public void exportMThree(HttpServletRequest request, HttpServletResponse response) {
        Calendar calendar = Calendar.getInstance();// 取当前日期。
        String imagePath = "src/main/resources/images/fenmian.png";
        //获得数据
        List<ItemInfo> itemInfos = new ArrayList<>();
        List<Map<String, Object>>itemMaps = new ArrayList<>();
        for (int i=0;i<10;i++){
            ItemInfo itemInfo=new ItemInfo();
            itemInfo.setName("电脑"+i);
            itemInfo.setCount(i);
            itemInfo.setPrice((i+1)*1000);
            Map<String, Object> itemMap = new HashMap<String, Object>();
            itemMap.put("name", "电脑"+i);
            itemMap.put("count", i);
            itemMap.put("price", (i+1)*1000);
            itemMaps.add(itemMap);
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("name", "李明");
        map.put("testValue", "freeMarker");
        map.put("date", new Date().toString());
        map.put("listIn", itemMaps);
        map.put("image",this.getImageBase(imagePath));
        try {
            WordUtils wordUtils=new WordUtils();
            wordUtils.exportToWordMTree(map,"templates/tup.ftl","用freemarker生成Word文档.doc",request, response);
        }  catch (Exception e) {
            e.printStackTrace();
        }
    }

    //获得图片的base64码
    @SuppressWarnings("deprecation")
    public String getImageBase(String src) {
        if(src==null||src==""){
            return "";
        }
        File file = new File(src);
        if(!file.exists()) {
            return "";
        }
        InputStream in = null;
        byte[] data = null;
        try {
            in = new FileInputStream(file);
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }
        try {
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);
}

WordUtils

  

/**
     * @Author: created by yeluo
     * @Description:
     * @param: [dataMap, ftlPath, request, response]
     * @return: org.springframework.core.io.InputStreamSource
     * @Date: 13:01 2022/3/10
     */
    public InputStreamSource exportToWordMTree(Map<String, Object> dataMap, String ftlPath,String outFileName, HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 纠正编码
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("utf-8");
        // ** 初始化配置文件**//*
        Configuration configuration = new Configuration();
        // ** 设置编码 **//*
        configuration.setDefaultEncoding("utf-8");
        //********
        configuration.setClassForTemplateLoading(WordUtils.class, "/");
        // 加载模板,通过Word转XML文件转换过来的
        Template template = configuration.getTemplate(ftlPath);
        //方式三
        //文件名称
        InputStreamSource file = createDocAndDonwload(dataMap, template, "D:/doc_freeM/", outFileName);
        InputStream fin = file.getInputStream();
        ServletOutputStream out;
        response.setContentType("application/msword");
        // 设置浏览器以下载的方式处理该文件
        response.setHeader("content-disposition", "attachment;filename=document.doc");
        out = response.getOutputStream();
        // 缓冲区
        byte[] buffer = new byte[512];
        int bytesToRead;
        // 通过循环将读入的Word文件的内容输出到浏览器中
        while ((bytesToRead = fin.read(buffer)) != -1) {
            out.write(buffer, 0, bytesToRead);
        }
        fin.close();
        if (out != null) {
            out.close();
        }
        return file;
    }

 @SuppressWarnings("unchecked")
    public InputStreamSource createDocAndDonwload(Map dataMap,Template template,String filePath,String fileName)
            throws IOException, TemplateException {
        //输出文件
        File outFile = new File(filePath+File.separator+fileName);
        //如果输出目标文件夹不存在,则创建
        if (!outFile.getParentFile().exists()){
            outFile.getParentFile().mkdirs();
        }
        //将模板和数据模型合并生成文件
        Writer outD = new OutputStreamWriter(new FileOutputStream(outFile),"UTF-8");
        Writer out = new BufferedWriter(outD);
        //生成文件
        template.process(dataMap, out);
        //生成随机的名称
        StringWriter outW = new StringWriter();
        Writer outBody = new BufferedWriter(outW, 10240);
        //将数据输出到模板
        template.process(dataMap, outBody);
        //关闭流
        out.flush();
        out.close();
        outBody.flush();
        outBody.close();
        return new ByteArrayResource(outW.toString().getBytes(StandardCharsets.UTF_8));
    }

测试

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值