EasyExcel实现导出并上传文件

该代码片段展示了如何将Java对象转换为List结构,用于生成Excel文件。使用EasyExcel库处理导出,结合自定义字段,并最终将生成的Excel文件上传到OSS存储服务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

导出文件的列,将每一列都包装成一个List然后返回一个大List

private static List<List<String>> getHeadList(List<String> headList, List<String> customerVirable, LinkedHashMap<String, String> headerMap) {
        List<List<String>> list = new ArrayList<>();
        for (String s : headList) {
            // 根据传递过来的s,找到他对应的中文表头
            List<String> strings = new ArrayList<>();
            strings.add(headerMap.get(s));
            list.add(strings);
        }
        // 将自定义字段添加进来
        for (String str : customerVirable) {
            List<String> strings = new ArrayList<>();
            strings.add(str);
            list.add(strings);
        }
        return list;
    }

被导出的数据,这里的数据可以是实体也可以是集合,注意lists和list的位置!

private List<List<String>> getLists(List<String> newHead, List<AccountVO> newList) {
        List<List<String>> lists = new ArrayList<>();
        for (AccountVO demoData : newList) {
            List<String> list = new ArrayList<>();
            // 在遍历的时候要严格按照表头的顺序来
            for (String str : newHead) {
                Object o = valueMap.get(str);
                if (Objects.isNull(o)) {
                    list.add(StrUtil.EMPTY);
                } else {
                    list.add(String.valueOf(o));
                }
            }
            lists.add(list);
        }
        return lists;
    }

导出并上传

// 行数据,需要将自定义的字段也添加进来
        List<AccountVO> newList = getNewList(content, systemExportFieldList);
        // 将要被导出的数据,先看看有多少个属性,然后再决定要遍历多少次,每次遍历都要把每一个实体的相同属性取出来
        List<List<String>> lists = getLists(newHead, newList);
        // 开始执行导出,同时设置样式
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        EasyExcelFactory.write(out)
                .registerWriteHandler(new CommentWriteHandler(TOTAL_COUNT,
                        queryAccountPageRequest.getUserId(), mdcLogId, jobLogByJobInstanceId, socketIOService))
                .registerWriteHandler(excelWidthStyleStrategy)
                .excelType(ExcelTypeEnum.XLSX)
                .head(head)
                .sheet()
                .doWrite(lists);
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(out.toByteArray());
        // 开始上传到oss
        try {
            String baseName = DateUtil.format(new Date(), "yyyyMMddHHmmss");
            String upload = objectStorageHelper.upload(OssKeyCenter.getExcelOssFileKey(PREFIX_NAME,
                    queryAccountPageRequest.getTenantId(), queryAccountPageRequest.getUserId(), baseName), byteArrayInputStream);
        } catch (Exception e) {
            log.error("上传报错", e);
        }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值