首页 > 解决方案 > 你如何使用java读取一个太大的excel文件?

问题描述

我正在使用 mac 和 Apache Netbeans 11.2

我想使用 java 读取一个 excel 文件,但它的行超过 50,000,并且它有近 60 列。因此,当我阅读它时,我收到一条错误消息:

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

这是我用来读取和打印 excel 文件的代码。

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class XlsxRead {

    public static void main(String[] args) throws FileNotFoundException, IOException, InvalidFormatException {

        try {
            File file = new File("/Users/gyungtaepark/Desktop/RawData.xlsx"); 
            FileInputStream fis = new FileInputStream(file);

            XSSFWorkbook wb = new XSSFWorkbook(fis);
            XSSFSheet sheet = wb.getSheetAt(0); 
            System.out.println("here");

            Iterator<Row> itr = sheet.iterator();  
            while (itr.hasNext()) {

                Row row = itr.next();

                Iterator<Cell> cellIterator = row.cellIterator();   //iterating over each column  
                while (cellIterator.hasNext()) {
                    Cell cell = cellIterator.next();
                    switch (cell.getCellType()) {
                        case Cell.CELL_TYPE_STRING:    //field that represents string cell type  
                            System.out.print(cell.getStringCellValue() + "\t\t\t");
                            break;
                        case Cell.CELL_TYPE_NUMERIC:    //field that represents number cell type  
                            System.out.print(cell.getNumericCellValue() + "\t\t\t");
                            break;
                        default:
                    }
                }
                System.out.println("");
            }
        } catch (IOException e) {
        }
    }
}

有没有办法读取这个文件?

我有一些不需要阅读的列,如果我删除它们,代码可以读取文件。

我想知道如何读取大文件或使用代码删除列,而无需在 excel 中手动删除它们。

标签: javaexcelmacosapache-poi

解决方案


推荐阅读