easypoi导出word文档(文本,表格)

文件模板

依赖导入

*坑:注意依赖版本 4.3.0+才支持多图片循环导出

<!-- word导出  方式:easypoi-->
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-base</artifactId>
            <version>4.3.0</version>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-web</artifactId>
            <version>4.3.0</version>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-annotation</artifactId>
            <version>4.3.0</version>
        </dependency>
        <!--注意:word中要使用循环等标签必须单独导入以下依赖-->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>ooxml-schemas</artifactId>
            <version>1.4</version>
        </dependency>

逻辑代码

注意:WordExportUtil包引 import cn.afterturn.easypoi.word.WordExportUtil,否则会造成table表格里的数据导不出来

    @RequestMapping(value = "/wordExportTest",method = RequestMethod.GET)
    public void wordExportTest(HttpServletResponse response) throws Exception {
        //封装数据
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("title", "你好啊");
        params.put("body", "一夜暴富,早日脱单");

        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        Map<String, Object> obj;
        for (int i = 0; i < 5; i++) {
            obj = new HashMap<String, Object>();
            obj.put("name", "abc-" + i);
            obj.put("age", i);
            obj.put("sex", "男-" + i);
            list.add(obj);
        }
        params.put("objs", list);

        //jar包获取不到文件路径
        //URLDecoder.decode() 解决获取中文名称文件路径乱码
        String templatePath = URLDecoder.decode(this.getClass().getClassLoader().getResource("mb/分析报告.docx").getPath(), "UTF-8");
        
        //生成word文档流
        XWPFDocument doc = WordExportUtil.exportWord07(templatePath, params);
        //设置响应体内容类型
        response.setContentType("application/octet-stream");
        //添加响应头
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("报告.docx", "UTF-8"));
        //暴露新添加的响应头
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        //将word文档流输出到输出流中
        doc.write(response.getOutputStream());
        //关闭流
        doc.close();
    }

  • 6
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值