java写入word表格(poi-tl)

1.导入依赖

<!--poi-tl-->
<dependency>
    <groupId>com.deepoove</groupId>
    <artifactId>poi-tl</artifactId>
    <version>1.12.0</version>
</dependency>

2.代码

自己创建模板。放在(resource/file)

    @GetMapping("/api/word")
    @ApiOperation(value = "接口文档下载", produces = "application/octet-stream")
    @ApiOperationSupport(order = 1)
    public void download(
	@RequestParam @NotBlank(message = "id不能为空") String id, HttpServletResponse response) throws Exception {
        try (InputStream resourceAsStream = getClass().getResourceAsStream("/file/word.docx");
             XWPFTemplate template = XWPFTemplate.compile(resourceAsStream);
             OutputStream out = response.getOutputStream();
             BufferedOutputStream bos = new BufferedOutputStream(out)) {
            //封装模型数据
            HashMap<String, Object> map = new HashMap<>();
            map.put("apiLabel", "apiLabel");
            map.put("apiPath", Texts.of("apiPath").color("0000FF").bold().create());
            map.put("returnFormat", "JSON");
            //apiParams  getApiParams方法获取一个List类型
            map.put("apiParams", Tables.create(getApiParams(data.getApiParams()).toArray(new RowRenderData[0])));
            //渲染数据
            template.render(map);
			 //以文件形式输出
        //      template.writeAndClose(new FileOutputStream(outputPath));//文件流

            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode防止中文乱码
            String fileName = URLEncoder.encode("测试"+LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss"))+"_授权文档", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".docx");

            template.write(bos);
        }
    }

3.效果

参考:

poi-tl的使用(通俗易懂,全面,内含动态表格实现 !)-CSDN博客

https://deepoove.com/poi-tl/

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值