簡體   English   中英

使用Apache POI將ArrayList中的數據插入Excel文件中的塊中

[英]Inserting data from arraylist in chunks in excel file using apache poi

我有以下格式的數據arraylist:

ArrayList> listResultData。 現在,集合包含大約11k +行要插入到excel中。 當我在excel中插入這11490行時, 插入記錄花了6個小時 ,這意味着它的性能很差。 無論如何,是否有一次將Excel中的數據以塊的形式一次插入1000行(這意味着在sql中應該有諸如executeBatch()之類的東西用於插入記錄 )。 行還包含4-5列。

以下是我一直在使用的代碼:

public boolean setArrayListData(String sheetName, ArrayList<ArrayList<String>> listResultData) {
    try {
        fis = new FileInputStream(path);
        workbook = new XSSFWorkbook(fis);

        int index = workbook.getSheetIndex(sheetName);

        if (index == -1)
            return false;

        sheet = workbook.getSheetAt(index);

        int colNum = 0;
        int rowNum = this.getRowCount(sheetName);
        rowNum++;
        for (ArrayList<String> al : listResultData) {   
            for (String s : al) {
                sheet.autoSizeColumn(colNum);
                row = sheet.getRow(rowNum - 1);
                if (row == null)
                    row = sheet.createRow(rowNum - 1);

                cell = row.getCell(colNum);
                if (cell == null)
                    cell = row.createCell(colNum);

                // cell style
                // CellStyle cs = workbook.createCellStyle();
                // cs.setWrapText(true);
                // cell.setCellStyle(cs);
                cell.setCellValue(s);
                //System.out.print("Cell Value :: "+s);
                colNum++;
            }
            rowNum++;
            colNum = 0;
            //System.out.println("");
        }

        fileOut = new FileOutputStream(path);
        workbook.write(fileOut);
        fileOut.close();
        workbook.close();
        fis.close();
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
    return true;
}

請建議!

代替XSSF,您可能想嘗試SXSSF XSSF的流擴展。 與xssf相比,在xssf中您可以訪問文檔中的所有行,這可能會導致性能或堆空間問題。sxssf允許您定義一個滑動窗口並限制對該窗口中行的訪問。 您可以使用new SXSSFWorkbook(int windowSize)在構建工作簿時指定窗口大小。 當您創建行並且行數超過指定的窗口大小時,具有最低索引的行將被刷新,並且不再存在於內存中。

SXSSF(流用戶模型API)上找到更多信息。

例:

// keep 100 rows in memory, exceeding rows will be flushed to disk
SXSSFWorkbook wb = new SXSSFWorkbook(100); 
    Sheet sh = wb.createSheet();
    for(int rownum = 0; rownum < 1000; rownum++){
        //When the row count reaches 101, the row with rownum=0 is flushed to disk and removed from memory, 
        //when rownum reaches 102 then the row with rownum=1 is flushed, etc. 
        Row row = sh.createRow(rownum);
        for(int cellnum = 0; cellnum < 10; cellnum++){
            Cell cell = row.createCell(cellnum);
            String address = new CellReference(cell).formatAsString();
            cell.setCellValue(address);
        }

    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM