首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用apache在excel文件中从数组中插入数据块

使用apache在excel文件中从数组中插入数据块
EN

Stack Overflow用户
提问于 2017-08-25 07:40:48
回答 1查看 1.2K关注 0票数 4

我有如下格式的数据数组:

ArrayList> listResultData.现在集合包含要插入到excel中的11k+行。当我在excel中插入这11490行时,花了6小时才插入记录,这意味着它的性能问题非常糟糕。是否一次以块的形式插入excel中的数据(意味着在sql中插入记录时应该有类似于executeBatch()的内容)。一行还包含4-5列。

以下是我一直使用的代码:

代码语言:javascript
复制
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;
}

请建议!!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-08-25 10:02:40

您可以尝试使用XSSF的流扩展SXSSF,而不是XSSF。与xssf不同,在xssf中,您可以访问文档中可能导致性能或堆空间的所有行,sxssf允许您定义一个滑动窗口,并限制对该窗口中行的访问。可以使用new SXSSFWorkbook(int windowSize)在工作簿的构造时指定窗口大小。然后,当您创建行并且行数超过指定的窗口大小时,索引最低的行将被刷新,并且不再在内存中。

流用户模型API( SXSSF )找到更多的信息

示例:

代码语言:javascript
复制
// 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);
        }

    }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45876531

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档