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

This commit is contained in:
RuoYi
2026-03-09 15:04:55 +08:00
parent d76f52b5ca
commit f82ea7942a

View File

@@ -106,6 +106,11 @@ public class ExcelUtil<T>
*/ */
public Map<String, String> sysDictMap = new HashMap<String, String>(); public Map<String, String> sysDictMap = new HashMap<String, String>();
/**
* 单元格样式缓存
*/
private Map<String, CellStyle> cellStyleCache = new HashMap<String, CellStyle>();
/** /**
* Excel sheet最大行数默认65536 * Excel sheet最大行数默认65536
*/ */
@@ -418,7 +423,7 @@ public class ExcelUtil<T>
Object val = this.getCellValue(row, entry.getKey()); Object val = this.getCellValue(row, entry.getKey());
// 如果不存在实例则新建. // 如果不存在实例则新建.
entity = (entity == null ? clazz.getDeclaredConstructor().newInstance() : entity); entity = (entity == null ? clazz.newInstance() : entity);
// 从map中得到对应列的field. // 从map中得到对应列的field.
Field field = (Field) entry.getValue()[0]; Field field = (Field) entry.getValue()[0];
Excel attr = (Excel) entry.getValue()[1]; Excel attr = (Excel) entry.getValue()[1];
@@ -1125,7 +1130,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
@@ -1202,9 +1207,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;
} }
@@ -1426,7 +1438,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);
} }