java写入word表格(poi-tl)

1.导入依赖



    com.deepoove
    poi-tl
    1.12.0

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 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.效果

java写入word表格(poi-tl)_第1张图片

参考:

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

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

你可能感兴趣的:(java,word)