SpringBoot集成easyexcel实现动态模板导出

news/2024/7/21 5:23:14 标签: spring boot, excel, 后端

添加依赖

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>3.3.2</version>
        </dependency>
            
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.2</version>
        </dependency>

查看easyexcel 开发文档,定义excel动态模板

根据自己需求:

image-20231111211640262

单属性用{} + 属性名填充,列表属性用{.} + 属性名填充

代码实战

导入请求,Controller层:

    @GetMapping("/export")
    @ApiOperation("导出盘库范围")
    public void export(@ApiParam("盘库任务id") String id, HttpServletResponse response) {
        storeInventoryTaskService.export(id, response);
    }

业务实现,主要是查询需导出的数据比较简单:主要,使用map设置属性,map键值与excel中属性名对应上

    public void export(String id, HttpServletResponse response) {
        StoreInventoryTaskDetailVo taskInfo = taskInfo(id);
        List<InventoryListVo> vos = rangeInfo(id);
        Map<String, Object> map = new HashMap<>();
        map.put("inventoryNo", taskInfo.getInventoryNo());
        map.put("storeName", taskInfo.getStoreName());
        map.put("startTime", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, taskInfo.getStartTime()));
        map.put("endTime", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, taskInfo.getEndTime()));
        // 自增序号
        AtomicInteger idx = new AtomicInteger();
        vos.forEach(el -> el.setIdx(idx.incrementAndGet()));
        map.put("list", vos);
        try {
            TemplateExcelUtil.downLoadExcel("盘库工单" + taskInfo.getInventoryNo(), "盘库工单模板.xlsx", map, response);
        } catch (Exception e) {
            throw new ServiceException("导出盘库工单报错");
        }
    }

核心类

TemplateExcelUtil.downLoadExcel

根据模板名称获取输入流,输出流也为固定套路,同时设置导出excel文件名,其余代码基本和官方文档保持一致即可

@Slf4j
public class TemplateExcelUtil {

    /**
     * 根据模板导出数据
     *
     * @param fileName   导出文件名
     * @param sourcePath resource/template文件夹下路径
     */
    public static void downLoadExcel(String fileName, String sourcePath, Map<String, Object> beanParams, HttpServletResponse response)
            throws Exception {
        try (OutputStream os = getOutputStream(fileName, response);
             InputStream is = TemplateExcelUtil.class.getClassLoader().getResourceAsStream("template/" + sourcePath);
             ExcelWriter excelWriter = EasyExcel.write(os).withTemplate(is).build()) {

            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
            excelWriter.fill(beanParams.get("list"), fillConfig, writeSheet);
            excelWriter.fill(beanParams, writeSheet);

            // 关闭流
            excelWriter.finish();
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * 导出文件时为Writer生成OutputStream.
     *
     * @param fileName 文件名
     * @param response response
     */
    private static OutputStream getOutputStream(String fileName,
                                                HttpServletResponse response) throws Exception {
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf8");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".xlsx");
            response.setHeader("Pragma", "public");
            response.setHeader("Cache-Control", "no-store");
            response.addHeader("Cache-Control", "max-age=0");
            return response.getOutputStream();
        } catch (IOException e) {
            throw new Exception("导出excel表格失败!", e);
        }
    }
}

经测试,导出效果如下:

image-20231111212613185


http://www.niftyadmin.cn/n/5172242.html

相关文章

【教3妹学编程-算法题】765. 情侣牵手

3妹&#xff1a;2哥2哥&#xff0c;你看到新闻了吗&#xff1f;襄阳健桥医院院长 公然“贩卖出生证明”&#xff0c; 真是太胆大包天了吧。 2哥 : 我也看到新闻了&#xff0c;7人被采取刑事强制措施。 就应该好好查查他们&#xff0c; 一查到底&#xff01; 3妹&#xff1a;真的…

ceph rados对象存储索引残留问题排查与处理

问题现象 对象存储存储桶无法删除&#xff0c;检查发现生命周期过期后存储桶中有文件残留&#xff0c;未完全删除&#xff0c;但实际访问文件时为404&#xff0c;通过s3cmd无法删除对象&#xff0c;且无报错。 问题定位 检查bucket当前状态&#xff0c;发现桶内有大量object…

Vuex:辅助函数:mapState,mapMutations,mapActions,mapGetters :VOA模式

说明 Vuex中提供了四个个比较常用的辅助函数&#xff1a;目的是将vuex中对应的 state(),mutaiions{},actions{},getters{}中的数据&#xff0c;函数映射出去&#xff0c;让我们在组件中可以更加简单的使用这些数据与函数 mapStatemapMutationsmapActionsmapGetters 使用案列…

抢量双11!抖音商城「官方立减」 缘何成为“爆单神器”?

10月20日抖音商城双11好物节正式开跑&#xff0c;仅仅三天&#xff0c;抖音商城整体GMV对比去年同期提升了200%&#xff0c;而在开跑一周后&#xff0c;一些品牌的销售额已经超过了今年整个618&#xff0c;可谓增势迅猛。其中&#xff0c;平台官方特别推出的「官方立减」玩法&a…

vue锚点链接

<el-tabs v-model"sName" tab-click"handleTabClick"><el-tab-pane label"公告正文" :name"1"></el-tab-pane><el-tab-pane label"串标公告" :name"2"></el-tab-pane> </el-tab…

土壤含水量的计算

土壤含水量的计算 土壤水分的表示方法 一般所说的土壤水分&#xff0c;实际上是指用烘干法在105-110摄氏度温度下能从土壤中被驱逐出来的水。土壤水分含量即土壤含水量&#xff0c;它是指土壤中所含有的水分的数量。土壤含水量可以用不同的方法表示&#xff0c;最常用的表示方…

【Java】I/O流—转换流、序列化流的初学者指南及RandomAccessFile类

&#x1f33a;个人主页&#xff1a;Dawn黎明开始 &#x1f380;系列专栏&#xff1a;Java ⭐每日一句&#xff1a;我不在意你曾堕落&#xff0c;我只在意你是否会崛起 &#x1f4e2;欢迎大家&#xff1a;关注&#x1f50d;点赞&#x1f44d;评论&#x1f4dd;收藏⭐️ 文章目录…

【研究】Splunk 字段是否被加工过

1: 背景: 最近用户有个疑问,就是有些字段的输出有点问题,不确定是否被加工过。 2: 查找问题: index=abc sourcetype=def123 发现字段: city_shanghai 的输出可能有点问题。 3: 排查问题: 先去这个splunk search head cluster 的页面: server 的查找如下: 登入so1 s…