Java小知识:List数据转换为Excel文件,再转为byte数组

背景:项目导入Excel数据的时候,需要把不符合规则的数据记录下来,并生成新的Excel文件上传到阿里云服务器,以便用户随时可以在导入记录里下载导入失败的Excel。
直接解析代码吧:

	/**
     * 功能描述:生成Excel文件
     *
     * @param Class clazz 自定义的生成Excel对应的对象
     */
	public static String exportExcelFile(List list,
                                         String fileName, String sheetName, Class clazz) throws Exception {
        if (ObjectUtils.isEmpty(list)) {
            return null;
        }
        String decodeToString = null;
        InputStream is = null;
        ByteArrayOutputStream bout = null;
        File file = null;
        OutputStream outputStream = null;
        try {
            bout = new ByteArrayOutputStream();
            //1.定义待生成的Excel文件路径,这里是获取当前项目路径
            String path = getPath() + "/" + fileName + ".xlsx";
            file = new File(path);
           //2.开始写入到文件
            outputStream = new FileOutputStream(file);
            EasyExcel.write(outputStream, clazz)
                    .head(clazz).registerWriteHandler(new ExcelAutoWithHandler())
                    .sheet(sheetName).doWrite(list);
            //3.把生成的文件的outputStream转为byte数组
            URL url = new URL("file://" + path);
            log.info("excel文件路径:" + url.getPath());
            URLConnection con = url.openConnection();
            con.setConnectTimeout(5 * 1000);
            is = con.getInputStream();
            int len;
            byte[] bs = new byte[1024];
            while ((len = is.read(bs)) != -1) {
                bout.write(bs, 0, len);
            }
            byte[] bytes = bout.toByteArray();
            //4.把数组转为base64返回以便上传
            decodeToString = Base64Utils.encodeToString(bytes);
        } catch (IOException e) {
            log.error("转成Excel文件发生异常");
            e.printStackTrace();
        } finally {
            if (is != null) {
                is.close();
            }
            if (is != null) {
                bout.flush();
            }
            if (is != null) {
                outputStream.close();
            }
            if (is != null) {
                file.delete();
            }
        }
        return decodeToString;
    }

这是定义的处理Excel格式的内部类

 private static class ExcelAutoWithHandler extends AbstractColumnWidthStyleStrategy {

    private Map<Integer, Map<Integer, Integer>> CACHE = new HashMap<>();

    @Override
    protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<CellData> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
        boolean needSetWidth = isHead || !CollectionUtils.isEmpty(cellDataList);
        if (needSetWidth) {
            Map<Integer, Integer> maxColumnWidthMap = CACHE.get(writeSheetHolder.getSheetNo());
            if (maxColumnWidthMap == null) {
                maxColumnWidthMap = new HashMap<>();
                CACHE.put(writeSheetHolder.getSheetNo(), maxColumnWidthMap);
            }

            Integer columnWidth = this.dataLength(cellDataList, cell, isHead);
            if (columnWidth >= 0) {
                if (columnWidth > 255) {
                    columnWidth = 255;
                }

                Integer maxColumnWidth = maxColumnWidthMap.get(cell.getColumnIndex());
                if (maxColumnWidth == null || columnWidth > maxColumnWidth) {
                    maxColumnWidthMap.put(cell.getColumnIndex(), columnWidth);
                    writeSheetHolder.getSheet().setColumnWidth(cell.getColumnIndex(), columnWidth * 256);
                }

            }
        }
    }

    private Integer dataLength(List<CellData> cellDataList, Cell cell, Boolean isHead) {
        if (isHead) {
            return cell.getStringCellValue().getBytes().length;
        } else {
            CellData cellData = cellDataList.get(0);
            CellDataTypeEnum type = cellData.getType();
            if (type == null) {
                return -1;
            } else {
                switch (type) {
                    case STRING:
                        return cellData.getStringValue().getBytes().length;
                    case BOOLEAN:
                        return cellData.getBooleanValue().toString().getBytes().length;
                    case NUMBER:
                        return cellData.getNumberValue().toString().getBytes().length;
                    default:
                        return -1;
                }
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值