性能优化建议ExcelUtils
Closed this issue · 2 comments
TomYule commented
ExcelUtils中的方法
exportExcelNoModuleHandler
`private Workbook exportExcelNoModuleHandler(List<?> data, Class clazz, boolean isWriteHeader, String sheetName,
boolean isXSSF) throws Exception {
Workbook workbook;
if (isXSSF) {
workbook = new XSSFWorkbook();
} else {
workbook = new HSSFWorkbook();
}
Sheet sheet;
if (null != sheetName && !"".equals(sheetName)) {
sheet = workbook.createSheet(sheetName);
} else {
sheet = workbook.createSheet();
}
Row row = sheet.createRow(0);
List<ExcelHeader> headers = Utils.getHeaderList(clazz);
if (isWriteHeader) {
// 写标题
for (int i = 0, length = headers.size(); i < length; i++) {
row.createCell(i).setCellValue(headers.get(i).getTitle());
}
}
// 写数据
Object _data;
for (int i = 0, length = data.size(); i < length; i++) {
row = sheet.createRow(i + 1);
_data = data.get(i);
for (int j = 0,h = headers.size(); j < h; j++) {
row.createCell(j).setCellValue(BeanUtils.getProperty(_data, headers.get(j).getFiled()));
}
}
return workbook;
}`
尽量减少对变量的重复计算
明确一个概念,对方法的调用,即使方法中只有一句语句,也是有消耗的,包括创建栈帧、调用方法时保护现场、调用方法完毕时恢复现场等。所以例如下面的操作:
TomYule commented
exportObjects2Excel方法优化
`
public void exportObjects2Excel(List<?> data, Class clazz, boolean isWriteHeader, String sheetName, boolean isXSSF, String targetPath){
FileOutputStream fos = null;
try{
fos = new FileOutputStream(targetPath);
exportExcelNoModuleHandler(data, clazz, isWriteHeader, sheetName, isXSSF).write(fos);
} catch(Exception e){
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
`
Crab2died commented
恩,jdk1.7有对资源管理的更好办法