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)

复制代码
public ApiResult<String> download2(
            HttpServletResponse response,
            @RequestParam(value = "apiCode", required = true) String apiCode
    ) throws Exception {
        String templatePath = getResourceFilePath("file","wordtempalte.docx");//resource下面有file文件夹,文件夹下面是模板
        ApiPermitInfo data = getPermitInfo(apiCode);
        writeword(templatePath, response,data);//写入文件
        return null;
    }
    public static String getResourceFilePath(String folderPath, String fileName) {
        // 构建资源路径
        String resourcePath = folderPath + "/" + fileName;
        // 获取资源的URL
        URL resourceUrl = ResourceUtil.class.getClassLoader().getResource(resourcePath);
        if (resourceUrl != null) {
            // 对于JAR包中的资源,直接返回URL的路径部分
            return resourceUrl.getPath();
        } else {
            // 资源不存在
            return null;
        }
    }
    private void writeword(String templatePath, HttpServletResponse response,ApiPermitInfo data) throws IOException {
        //解析模板
        XWPFTemplate template = XWPFTemplate.compile(templatePath);
        //封装模型数据
        HashMap<String, Object> map = new HashMap<>();
        map.put("apiLabel","apiLabel");
        map.put("apiPath", Texts.of("apiPath").color("0000FF").bold().create());
        
        //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");
        String formattedNow = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss"));
        response.setHeader("Content-disposition", "attachment;filename=\"" + formattedNow+".docx" + "\"");
        OutputStream out = response.getOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(out);
        template.write(bos);//浏览器下载
        PoitlIOUtils.closeQuietlyMulti(template, bos, out);
        return;
    }

3.效果

参考:

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

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

相关推荐
To Be Clean Coder15 小时前
【Spring源码】getBean源码实战(三)
java·mysql·spring
Wokoo715 小时前
开发者AI大模型学习与接入指南
java·人工智能·学习·架构
电摇小人15 小时前
我的“C++之旅”(博客之星主题作文)
java·开发语言
资生算法程序员_畅想家_剑魔15 小时前
Java常见技术分享-23-多线程安全-总结
java·开发语言
萧曵 丶16 小时前
ArrayList 和 HashMap 自动扩容机制详解
java·开发语言·面试
这是程序猿16 小时前
基于java的ssm框架学生作业管理系统
java·开发语言·spring boot·spring·学生作业管理系统
千百元16 小时前
限制网段访问服务器端口63790
java·网络·mybatis
宋情写16 小时前
JavaAI03-数据来源
java
钦拆大仁16 小时前
JDK17新特性
java
小程故事多_8016 小时前
Spring AI 赋能 Java,Spring Boot 快速落地 LLM 的企业级解决方案
java·人工智能·spring·架构·aigc