janssen-dev
janssen-dev

Reputation: 2771

Apache POI only read the first row of a large Excel file

Can I read only the first row of an Excel file with Apache POI? I don't want to read the whole file because it has 50,000 rows and takes up to 10 minutes to read (performance is a disaster). I am getting the bytes via file upload. My options are a byte array or an InputStream. Right now I am doing this:

Workbook workbook = new XSSFWorkbook(excelByteStream); //This line takes a lot of time, while debugging up to 10 minutes
Sheet firstSheet = workbook.getSheetAt(0);
DataFormatter df = new DataFormatter();
List<ColumnPanel> columnPanels = new ArrayList<>();
int i = 0;

for (Cell cell : firstSheet.getRow(0))
{
    columnPanels.add(new ColumnPanel(df.formatCellValue(cell), i++));
}

Upvotes: 1

Views: 7702

Answers (1)

Quan Tang
Quan Tang

Reputation: 11

InputStream is = new FileInputStream(new File("/path/to/workbook.xlsx"));

Workbook workbook = StreamingReader.builder() .rowCacheSize(100) .bufferSize(4096) .open(is);

Sheet sheet = workBook.getSheetAt(0);

Row firstRow = sheet.rowIterator().next();

You can use this lib: https://github.com/monitorjbl/excel-streaming-reader

Good guide: Apache POI Streaming (SXSSF) for Reading

Upvotes: 1

Related Questions