Tung Vo
Tung Vo

Reputation: 2549

SXSSFSheet autoSizeColumn error on apache poi 4.1.2

My project using Spring Boot. I try to export data to excel file with org.apache.poi 4.1.2 , i use method autoSizeColumn to auto size column

headerRow.forEach(item -> {
  sheet.autoSizeColumn(item.getColumnIndex());
});

but i get the error

java.lang.IllegalStateException: Could not auto-size column. Make sure the column was tracked prior to auto-sizing the column.
at org.apache.poi.xssf.streaming.SXSSFSheet.autoSizeColumn(SXSSFSheet.java:1591)
at org.apache.poi.xssf.streaming.SXSSFSheet.autoSizeColumn(SXSSFSheet.java:1545)

how to fix this error

Upvotes: 3

Views: 8395

Answers (2)

Tmh
Tmh

Reputation: 1511

I have fixed the above issue with the following, do this only after you are done rendering everything on to the sheet

if you have list for columns then the following will work fine.

// autoSizing of the columns

for (int i = 0; i < columns.size(); i++) {
  workbookSheet.trackAllColumnsForAutoSizing();
  workbookSheet.autoSizeColumn(i);
}

For your case the below will work.

headerRow.forEach(item -> {
  sheet.trackAllColumnsForAutoSizing();
  sheet.autoSizeColumn(item.getColumnIndex());
});

Upvotes: 0

Tung Vo
Tung Vo

Reputation: 2549

I have fixed this issue following this link SXSSFSheet.autoSizeColumn is throwing IllegalStateException

i resolve this issue by using the method public void trackAllColumnsForAutoSizing() of class SXSSFSheet

public void trackAllColumnsForAutoSizing()

Tracks all columns in the sheet for auto-sizing. If this is called, individual columns do not need to be tracked. Because determining the best-fit width for a cell is expensive, this may affect the performance.

Since: 3.14beta1

Upvotes: 3

Related Questions