优化Excel自定义格式样式重复创建问题

This commit is contained in:
RuoYi
2026-03-09 15:14:51 +08:00
parent c5cd75fe17
commit 316117524d

View File

@@ -79,6 +79,11 @@ public class ExcelUtil<T>
public static final String[] FORMULA_STR = { "=", "-", "+", "@" }; public static final String[] FORMULA_STR = { "=", "-", "+", "@" };
/**
* 单元格样式缓存
*/
private Map<String, CellStyle> cellStyleCache = new HashMap<String, CellStyle>();
/** /**
* Excel sheet最大行数默认65536 * Excel sheet最大行数默认65536
*/ */
@@ -976,7 +981,7 @@ public class ExcelUtil<T>
* 添加单元格 * 添加单元格
*/ */
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public Cell addCell(Excel attr, Row row, T vo, Field field, int column) public Cell addCell(Excel attr, Row row, T vo, Field field, int column)
{ {
Cell cell = null; Cell cell = null;
try try
@@ -1043,9 +1048,16 @@ public class ExcelUtil<T>
*/ */
private CellStyle createCellStyle(CellStyle cellStyle, String format) private CellStyle createCellStyle(CellStyle cellStyle, String format)
{ {
String key = cellStyle.getIndex() + "|" + format;
CellStyle cached = cellStyleCache.get(key);
if (cached != null)
{
return cached;
}
CellStyle style = wb.createCellStyle(); CellStyle style = wb.createCellStyle();
style.cloneStyleFrom(cellStyle); style.cloneStyleFrom(cellStyle);
style.setDataFormat(wb.getCreationHelper().createDataFormat().getFormat(format)); style.setDataFormat(wb.getCreationHelper().createDataFormat().getFormat(format));
cellStyleCache.put(key, style);
return style; return style;
} }
@@ -1241,7 +1253,7 @@ public class ExcelUtil<T>
{ {
try try
{ {
Object instance = excel.handler().getDeclaredConstructor().newInstance(); Object instance = excel.handler().newInstance();
Method formatMethod = excel.handler().getMethod("format", new Class[] { Object.class, String[].class, Cell.class, Workbook.class }); Method formatMethod = excel.handler().getMethod("format", new Class[] { Object.class, String[].class, Cell.class, Workbook.class });
value = formatMethod.invoke(instance, value, excel.args(), cell, this.wb); value = formatMethod.invoke(instance, value, excel.args(), cell, this.wb);
} }