@Slf4j
@Component
public class ExcelUtil {
@Value("${excel_max_rows}")
private static int excelMaxRows;
private static final int EXCEL_MAX_ROWS = excelMaxRows;
public static <T> void excelExport(String[] labels, String[] props, List<T> list, String fileNamePre,
HttpServletResponse response) {
if (list.size() > EXCEL_MAX_ROWS) {
excelRowsOverReturn(response);
return;
}
SXSSFWorkbook wb = null;
Sheet sheet = null;
Row row = null;
Cell cell = null;
OutputStream os = null;
try {
wb = new SXSSFWorkbook();
wb.setCompressTempFiles(true);
sheet = wb.createSheet();
row = sheet.createRow(0);
for (int i = 0; i < labels.length; i++) {
cell = row.createCell(i);
cell.setCellValue(labels[i]);
}
for (int i = 0; i < list.size(); i++) {
row = sheet.createRow(i + 1);
for (int j = 0; j < labels.length; j++) {
cell = row.createCell(j);
cell.setCellValue(getFieldValueByFieldName(list.get(i), props[j]));
}
}
String now = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
String fileName = fileNamePre + now + ".xlsx";
os = response.getOutputStream();
response.setHeader("Content-Disposition", "attachment;filename="
+ URLEncoder.encode(fileName, "UTF-8"));
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
wb.write(os);
os.flush();
} catch (Exception e) {
log.error(ResultCode.IO_FAIL.message(), e);
} finally {
closeIO(wb, os);
}
}
private static void excelRowsOverReturn(HttpServletResponse response) {
OutputStream os = null;
try {
os = response.getOutputStream();
response.setHeader("code", ResultCode.EXCEL_MAX_ROWS_FAIL.code().toString());
response.setHeader("message", URLEncoder.encode(
ResultCode.EXCEL_MAX_ROWS_FAIL.message() + EXCEL_MAX_ROWS, "UTF-8"));
} catch (Exception e) {
log.error(ResultCode.IO_FAIL.message(), e);
} finally {
try {
if (os != null) {
os.close();
}
} catch (IOException e) {
log.error(ResultCode.IO_FAIL.message(), e);
}
}
}
private static String getFieldValueByFieldName(Object object, String fieldName) {
String fieldValue = null;
try {
Field field = object.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
return field.get(object).toString();
} catch (Exception e) {
return fieldValue;
}
}
private static void closeIO(SXSSFWorkbook wb, OutputStream os) {
if (wb != null) {
wb.dispose();
}
try {
if (os != null) {
os.close();
}
} catch (IOException e) {
log.error(ResultCode.IO_FAIL.message(), e);
}
try {
if (wb != null) {
wb.close();
}
} catch (IOException e) {
log.error(ResultCode.IO_FAIL.message(), e);
}
}
}