欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

java使用EasyExcel導出上萬數(shù)據(jù)如何避免OOM

 更新時間:2024年11月11日 11:27:34   作者:鐘林@  
本文主要介紹了使用EasyExcel導出大量數(shù)據(jù)時避免OOM問題的方法,通過分頁查詢和分批次寫入Excel,可以有效避免內(nèi)存溢出,并提供了一個封裝好的工具類,簡化了導出代碼的編寫

一、前言

Excel 導出功能:大數(shù)據(jù)量的情況下,很容易出現(xiàn) OOM。

數(shù)據(jù)量不大沒有什么問題,做法是直接查全量數(shù)據(jù),然后直接往Excel里寫。但是當數(shù)據(jù)量逐漸多了起來后,達到一萬多條,導出的時候就會報OOM。然后換成了阿里開源的EasyExcel,但是導出的時候也不太穩(wěn)定,偶爾也會出現(xiàn)OOM。所以應(yīng)該是數(shù)據(jù)量太大了,在寫入的時候把內(nèi)存占滿了。解決方式:放棄了查全量數(shù)據(jù)一次性寫入Excel的做法,采用分頁查詢,分批次寫入Excel的方式,果然不會出現(xiàn)OOM了。

封裝了一個EasyExcel的導出工具類,這樣只要在分頁查詢的基礎(chǔ)上寫少量的代碼,就可以實現(xiàn)分批次寫入Excel,簡化代碼的編寫并且解決OOM的問題。

二、實現(xiàn)

@Slf4j
public abstract class EasyExcelExport<T, S> {

    /**
     * EasyExcel導出Excel表格,每個sheet默認最大10萬條數(shù)據(jù)
     *
     * @param fileName  excel文件前綴名
     * @param sheetName 表頁名
     */
    public void easyExcelBatchExport(String fileName, String sheetName, HttpServletResponse response) {
        this.easyExcelBatchExport(fileName, sheetName, 100000, response);
    }

    /**
     * 分批次導出excel數(shù)據(jù)
     *
     * @param fileName  excel文件前綴名
     * @param sheetSize 每個sheet的數(shù)據(jù)量,默認10萬,excel有限制不能大于1048576
     * @param sheetName 表頁名
     */
    public void easyExcelBatchExport(String fileName, String sheetName, Integer sheetSize, HttpServletResponse response) {
        fileName = fileName + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + ".xlsx";
        int currentSheet = 1;   // 當前處于第幾個sheet
        int totalLine = 0;      // 總共寫入的條數(shù)
        int currentBatch = 1;   // 當前寫入excel的批次(第幾頁)
        int lineNum = 1;        // 行號,當前寫入的是第幾條數(shù)據(jù)

        long startTime = System.currentTimeMillis();
        try {
            response.setCharacterEncoding("utf-8");
            // 告訴瀏覽器用什么軟件可以打開此文件
            response.setHeader("content-Type", "application/vnd.ms-excel");
            // 下載文件的默認名稱
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));

            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]).build();
            WriteSheet sheet = EasyExcel.writerSheet(sheetName).build();

            while (true) {
                // 獲取數(shù)據(jù),然后currentBatch+1,下次調(diào)用就會獲取新的數(shù)據(jù)
                List<S> sourceDataList = getData(currentBatch);
                currentBatch++;

                List<T> exportEntityList = new ArrayList<>();
                if (CollUtil.isNotEmpty(sourceDataList)) {
                    totalLine += sourceDataList.size();
                    log.info("EasyExcel開始寫入第{}批數(shù)據(jù),當前批次數(shù)據(jù)大小為{}", currentBatch - 1, sourceDataList.size());
                    for (S sourceData : sourceDataList) {
                        exportEntityList.add(convertSourceData2ExportEntity(sourceData, lineNum));
                        lineNum++;

                        // 當前sheet數(shù)據(jù)已經(jīng)到達最大值,將當前數(shù)據(jù)全寫入當前sheet,下一條數(shù)據(jù)就會寫入新sheet
                        if (lineNum > sheetSize) {
                            excelWriter.write(exportEntityList, sheet);
                            exportEntityList.clear();
                            lineNum = 1;
                            currentSheet++;
                            sheet = EasyExcel.writerSheet(sheetName + currentSheet).build();
                        }
                    }

                    // 寫入excel
                    excelWriter.write(exportEntityList, sheet);
                } else {
                    // 未獲取到數(shù)據(jù),結(jié)束
                    break;
                }
            }
            excelWriter.finish();
        } catch (Exception e) {
            log.error("EasyExcel導出異常", e);
        }

        log.info("EasyExcel導出數(shù)據(jù)結(jié)束,總數(shù)據(jù)量為{},耗時{}ms", totalLine, (System.currentTimeMillis() - startTime));
    }

    /**
     * 不分批次導出excel。一次性獲取所有數(shù)據(jù)寫入excel,確定數(shù)據(jù)量不大時可以使用該方法,數(shù)據(jù)量過大時使用分批次導出,否則會OOM
     *
     * @param fileName  excel文件前綴名
     * @param sheetName 表頁名
     */
    public void easyExcelExport(String fileName, String sheetName, HttpServletResponse response) {
        fileName = fileName + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + ".xlsx";
        int totalLine = 0;      // 總共寫入的條數(shù)
        int lineNum = 1;        // 行號,當前寫入的是第幾條數(shù)據(jù)

        long startTime = System.currentTimeMillis();
        try {
            response.setCharacterEncoding("utf-8");
            // 告訴瀏覽器用什么軟件可以打開此文件
            response.setHeader("content-Type", "application/vnd.ms-excel");
            // 下載文件的默認名稱
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));

            List<S> sourceDataList = getData(1);
            List<T> exportEntityList = new ArrayList<>();
            if (CollUtil.isNotEmpty(sourceDataList)) {
                totalLine += sourceDataList.size();
                log.info("EasyExcel開始寫入數(shù)據(jù),數(shù)據(jù)大小為{}", sourceDataList.size());
                for (S sourceData : sourceDataList) {
                    exportEntityList.add(convertSourceData2ExportEntity(sourceData, lineNum));
                    lineNum++;
                }
            }
            response.setCharacterEncoding("utf-8");
            // 告訴瀏覽器用什么軟件可以打開此文件
            response.setHeader("content-Type", "application/vnd.ms-excel");
            // 下載文件的默認名稱
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
            EasyExcel.write(response.getOutputStream(), (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]).sheet(sheetName).doWrite(exportEntityList);
        } catch (Exception e) {
            log.error("EasyExcel導出異常", e);
        }

        log.info("EasyExcel導出數(shù)據(jù)結(jié)束,總數(shù)據(jù)量為{},耗時{}ms", totalLine, (System.currentTimeMillis() - startTime));
    }

    /**
     * 將原數(shù)據(jù)對象轉(zhuǎn)換為需要導出的目標對象
     *
     * @param sourceData 原對象
     * @param lineNum    行號
     */
    public abstract T convertSourceData2ExportEntity(S sourceData, Integer lineNum);

    /**
     * 獲取原始數(shù)據(jù),通過currentBatch參數(shù)分頁獲取數(shù)據(jù)。
     *
     * @param currentBatch 獲取第幾批(頁)數(shù)據(jù),通過該參數(shù)分頁查詢,每次調(diào)用自動遞增。不分批次導出時可以忽略該參數(shù)
     */
    public abstract List<S> getData(int currentBatch);

}

首先,這是EasyExcelExport是一個抽象類,指定了泛型 T 和 S,T是target目標類,也就是導出時對應(yīng)的類,S是source原對象所對應(yīng)的類。

EasyExcelExport里還有兩個抽象方法,getData() 和 convertSourceData2ExportEntity() 。

這兩個方法是需要在平時使用時自己去實現(xiàn)的,getData是數(shù)據(jù)查詢的方法,可以在這里面去實現(xiàn)分頁查詢的邏輯,currentBatch參數(shù)是用來控制分頁查詢頁碼的,從1開始,會自動遞增。如果確定數(shù)據(jù)量不大不需要分批次導出的話,那么getData()里只需要進行普通的查詢即可,忽略currentBatch參數(shù)不用分頁查詢。還有一個方法是convertSourceData2ExportEntity(),這個是用來將對象S轉(zhuǎn)為對象T的方法,因為從數(shù)據(jù)庫查詢或者是從其他地方獲取到的對象類型可能是S,而導出時需要的對象類型是T,所以通過該方法進行對象轉(zhuǎn)換。

最核心的是 easyExcelBatchExport() 方法,里面有一個while循環(huán),while循環(huán)里首先會去調(diào)用getData()方法獲取數(shù)據(jù),然后將currentBatch加1便于下次獲取數(shù)據(jù),接下來有個for循環(huán)去進行對象的轉(zhuǎn)換并添加到exportEntityList集合中,這個集合中裝的是最終寫到Excel里的對象。當轉(zhuǎn)換完成后就將當前批次的數(shù)據(jù)寫入Excel中,然后進行下一次循環(huán),當getData()方法未獲取到數(shù)據(jù)時,就結(jié)束循環(huán)。

同時支持指定每個sheet頁的最大行數(shù)。在對對象進行轉(zhuǎn)換時有一個判斷,當前sheet頁的數(shù)據(jù)是否到達指定值,到達后,直接寫入excel,然后新建一個sheet頁,這樣新的數(shù)據(jù)就會寫入新的sheet頁。

使用

那么如何使用這個工具類呢。很簡單,只要new出EasyExcelExport的對象,然后實現(xiàn)一下 convertSourceData2ExportEntity() 方法和 getData() 方法即可,然后再根據(jù)需要去調(diào)用不同的導出方法即可。導出方法有指定和不指定sheet數(shù)據(jù)頁大小的分批寫入方法 easyExcelBatchExport() 和不分批次直接一次性寫入的 easyExcelExport() 方法。

下面通過一個小案例展示一下。假設(shè)現(xiàn)在有個導出用戶列表的需求,數(shù)據(jù)庫User表對應(yīng)的是UserPO類:

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class UserPO {

    private Long id;

    /**
     * 用戶編號
     */
    private String code;

    /**
     * 姓名
     */
    private String name;

    /**
     * 手機號碼
     */
    private String phone;

    /**
     * 性別。1-男,2-女
     */
    private Integer sex;

}

導出對應(yīng)的類是UserExportEntity:

@Data
public class UserExportEntity {

    @ColumnWidth(10)
    @ContentStyle(horizontalAlignment = HorizontalAlignmentEnum.CENTER, verticalAlignment = VerticalAlignmentEnum.CENTER)
    @ExcelProperty(index = 0, value = "序號")
    private Integer line;

    @ColumnWidth(35)
    @ContentStyle(horizontalAlignment = HorizontalAlignmentEnum.CENTER, verticalAlignment = VerticalAlignmentEnum.CENTER)
    @ExcelProperty(index = 1, value = "用戶編號")
    private String code;

    @ColumnWidth(35)
    @ContentStyle(horizontalAlignment = HorizontalAlignmentEnum.CENTER, verticalAlignment = VerticalAlignmentEnum.CENTER)
    @ExcelProperty(index = 2, value = "姓名")
    private String name;

    @ColumnWidth(35)
    @ContentStyle(horizontalAlignment = HorizontalAlignmentEnum.CENTER, verticalAlignment = VerticalAlignmentEnum.CENTER)
    @ExcelProperty(index = 3, value = "手機號碼")
    private String phone;

    @ColumnWidth(10)
    @ContentStyle(horizontalAlignment = HorizontalAlignmentEnum.CENTER, verticalAlignment = VerticalAlignmentEnum.CENTER)
    @ExcelProperty(index = 4, value = "性別")
    private String sexStr;

    @ColumnWidth(10)
    @ContentStyle(horizontalAlignment = HorizontalAlignmentEnum.CENTER, verticalAlignment = VerticalAlignmentEnum.CENTER)
    @ExcelProperty(index = 5, value = "fieldA")
    private String fieldA;

    @ColumnWidth(10)
    @ContentStyle(horizontalAlignment = HorizontalAlignmentEnum.CENTER, verticalAlignment = VerticalAlignmentEnum.CENTER)
    @ExcelProperty(index = 6, value = "fieldB")
    private String fieldB;

    @ColumnWidth(10)
    @ContentStyle(horizontalAlignment = HorizontalAlignmentEnum.CENTER, verticalAlignment = VerticalAlignmentEnum.CENTER)
    @ExcelProperty(index = 7, value = "fieldC")
    private String fieldC;

    @ColumnWidth(10)
    @ContentStyle(horizontalAlignment = HorizontalAlignmentEnum.CENTER, verticalAlignment = VerticalAlignmentEnum.CENTER)
    @ExcelProperty(index = 8, value = "fieldD")
    private String fieldD;

    @ColumnWidth(10)
    @ContentStyle(horizontalAlignment = HorizontalAlignmentEnum.CENTER, verticalAlignment = VerticalAlignmentEnum.CENTER)
    @ExcelProperty(index = 9, value = "fieldE")
    private String fieldE;

    @ColumnWidth(10)
    @ContentStyle(horizontalAlignment = HorizontalAlignmentEnum.CENTER, verticalAlignment = VerticalAlignmentEnum.CENTER)
    @ExcelProperty(index = 10, value = "fieldF")
    private String fieldF;

    @ColumnWidth(10)
    @ContentStyle(horizontalAlignment = HorizontalAlignmentEnum.CENTER, verticalAlignment = VerticalAlignmentEnum.CENTER)
    @ExcelProperty(index = 11, value = "fieldG")
    private String fieldG;

    @ColumnWidth(10)
    @ContentStyle(horizontalAlignment = HorizontalAlignmentEnum.CENTER, verticalAlignment = VerticalAlignmentEnum.CENTER)
    @ExcelProperty(index = 12, value = "fieldH")
    private String fieldH;

    @ColumnWidth(10)
    @ContentStyle(horizontalAlignment = HorizontalAlignmentEnum.CENTER, verticalAlignment = VerticalAlignmentEnum.CENTER)
    @ExcelProperty(index = 13, value = "fieldI")
    private String fieldI;

}

先測試一下不分批次導出,導出123456條數(shù)據(jù)。

    @GetMapping("/testExport")
    public void testExport(HttpServletResponse response) {
        new EasyExcelExport<UserExportEntity, UserPO>() {
            @Override
            public UserExportEntity convertSourceData2ExportEntity(UserPO sourceData, Integer lineNum) {
                UserExportEntity entity = new UserExportEntity();
                entity.setLine(lineNum);
                entity.setCode(sourceData.getCode());
                entity.setName(sourceData.getName());
                entity.setPhone(sourceData.getPhone());
                entity.setSexStr(Objects.equals(sourceData.getSex(), 1) ? "男" : Objects.equals(sourceData.getSex(), 2) ? "女" : StrUtil.EMPTY);
                return entity;
            }

            @Override
            public List<UserPO> getData(int currentBatch) {
                List<UserPO> userPOList = new ArrayList<>();
                // 模擬查詢數(shù)據(jù)庫,假設(shè)每次查詢會查出123456條數(shù)據(jù)
                for (int i = 0; i < 123456; i++) {
                    userPOList.add(UserPO.builder()
                            .code("USER_" + RandomUtil.randomString("1234567890", 6))
                            .name(RandomUtil.randomString("qwertyuiopasdfghjklzxcvbnm", 10))
                            .phone("138" + RandomUtil.randomString("1234567890", 8))
                            .sex(RandomUtil.randomInt(1, 3))
                            .build());
                }
                log.info("userPOList-->{}", JSONUtil.toJsonStr(userPOList));
                return userPOList;
            }
        }.easyExcelExport("測試不分批次導出", "測試不分批次導出", response);
    }

為了更清晰地看到效果,我將內(nèi)存大小限制為128M。

調(diào)用一下測試接口,可以看到,導出十幾萬條數(shù)據(jù)時發(fā)生了OOM。

再來看看分批次導出的效果,模擬一下分頁查詢,假設(shè)有200頁數(shù)據(jù),每頁8888條,一共是170多萬條數(shù)據(jù)。

    @GetMapping("/testBatchExport")
    public void testBatchExport(HttpServletResponse response) {
        new EasyExcelExport<UserExportEntity, UserPO>() {
            @Override
            public UserExportEntity convertSourceData2ExportEntity(UserPO sourceData, Integer lineNum) {
                UserExportEntity entity = new UserExportEntity();
                entity.setLine(lineNum);
                entity.setCode(sourceData.getCode());
                entity.setName(sourceData.getName());
                entity.setPhone(sourceData.getPhone());
                entity.setSexStr(Objects.equals(sourceData.getSex(), 1) ? "男" : Objects.equals(sourceData.getSex(), 2) ? "女" : StrUtil.EMPTY);
                return entity;
            }

            @Override
            public List<UserPO> getData(int currentBatch) {
                // 模擬分頁查詢,假設(shè)數(shù)據(jù)庫中有200頁數(shù)據(jù)
                if (currentBatch <= 200) {
                    List<UserPO> userPOList = new ArrayList<>();
                    // 模擬查詢數(shù)據(jù)庫,假設(shè)每次查詢會查出8888條數(shù)據(jù)
                    for (int i = 0; i < 8888; i++) {
                        userPOList.add(UserPO.builder()
                                .code("USER_" + RandomUtil.randomString("1234567890", 6))
                                .name(RandomUtil.randomString("qwertyuiopasdfghjklzxcvbnm", 10))
                                .phone("138" + RandomUtil.randomString("1234567890", 8))
                                .sex(RandomUtil.randomInt(1, 3))
                                .build());
                    }
                    return userPOList;
                } else {
                    return new ArrayList<>();
                }
            }
        }.easyExcelBatchExport("測試分批次導出", "測試分批次導出", response);
    }

通過分批次寫入Excel的方式,成功導出了170多萬條數(shù)據(jù),相較于不分批次導出,效果顯而易見。而且通過調(diào)用工具類的方式,進一步簡化了導出時代碼的編寫。

到此這篇關(guān)于java使用EasyExcel導出上萬數(shù)據(jù)如何避免OOM的文章就介紹到這了,更多相關(guān)java EasyExcel導出數(shù)據(jù)避免OOM內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論