Trong quá trình xuất dữ liệu sang định dạng Excel với easypoi, có thể gặp lỗi: "The maximum number of cell styles was exceeded. You can define up to 64000 styles in a .xlsx workbook".
Để giải quyết vấn đề này, bạn có thể tái sử dụng các kiểu dáng đã được định nghĩa.
package com.example.excel.utils;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.afterturn.easypoi.excel.export.styler.ExcelExportStylerDefaultImpl;
import org.apache.poi.ss.usermodel.*;
import java.util.Objects;
public class CustomExcelStyle extends ExcelExportStylerDefaultImpl {
private CellStyle customNumberStyle;
public CustomExcelStyle(Workbook wb) {
super(wb);
initializeStyles();
}
private void initializeStyles() {
if (Objects.isNull(customNumberStyle)) {
customNumberStyle = workbook.createCellStyle();
customNumberStyle.setAlignment(HorizontalAlignment.CENTER);
customNumberStyle.setVerticalAlignment(VerticalAlignment.CENTER);
//customNumberStyle.setDataFormat((short) BuiltinFormats.getBuiltinFormat("0.00"));
//customNumberStyle.setWrapText(true);
}
}
@Override
public CellStyle getStyle(boolean isDefault, ExcelExportEntity entity) {
if (entity != null && entity.getType() == 10) {
return customNumberStyle;
}
return super.getStyle(isDefault, entity);
}
}
Sử dụng:
ExportParams params = new ExportParams("Xuất Dữ Liệu", "Dữ Liệu Tra Cứu", ExcelType.XSSF);<br></br>
params.setStyle(CustomExcelStyle.class); // Thiết lập kiểu số tự định nghĩa
Lý do gây ra vấn đề là từ việc gọi hàm createCellStyle():
workbook.createCellStyle();
Hàm này dẫn đến phương thức StyleTable#createCellStyle trong thư viện POI:
/**
* Tạo một kiểu dáng ô trong bảng kiểu dáng.
* Lưu ý - Người dùng cuối nên gọi {@link XSSFWorkbook#createCellStyle()}
* thay vì làm việc trực tiếp với bảng kiểu dáng.
* @throws IllegalStateException nếu số lượng tối đa của kiểu dáng ô đã đạt giới hạn.
*/
public XSSFCellStyle createCellStyle() {
if (getStyleCount() > MAX_STYLE_LIMIT) {
throw new IllegalStateException("Số lượng tối đa của kiểu dáng ô đã vượt mức. " +
"Bạn có thể định nghĩa tới " + MAX_STYLE_LIMIT + " kiểu dáng trong một Workbook .xlsx");
}
CTXf xf = CTXf.Factory.newInstance();
xf.setNumFmtId(0);
xf.setFontId(0);
xf.setFillId(0);
xf.setBorderId(0);
xf.setXfId(0);
int index = addCellXf(xf);
return new XSSFCellStyle(index - 1, this, theme);
}
MAX_STYLE_LIMIT = 64000 Việc đặt giới hạn này là cần thiết để tránh tạo quá nhiều đối tượng CellStyle. Nếu bạn có cách cải thiện hơn cho vấn đề tái sử dụng kiểu dáng khi xuất file bằng easypoi, hãy chia sẻ ý kiến!