java大量数据导出excel不占内存的方法
解决方法:
使用SXSSFWorkbook好处就是导出excel时不占用运行内存,它会把excel数据存放在磁盘的临时文件中保存,下面的1000指的是只会缓存1000条数据在代码运行内存中,设置小点不占缓存好点。
SXSSFWorkbook wb3 = new SXSSFWorkbook(1000); //flush
wb3.setCompressTempFiles(true);
//获取表头样式
XSSFCellStyle style = (XSSFCellStyle) wb3.createCellStyle();
Font font = wb3.createFont();
ExcelUtil.createCellStyle(style, null, font);
SXSSFSheet sheet = null;
Cell otherRowCell = null;
Row otherRow = null;
//创建表单
sheet= wb3.createSheet("表1名称");
otherRow = sheet.createRow(0);//创建第一行
for (int j = 0; j < 10; j++) {//在第一行中创建10列
otherRowCell = otherRow.createCell(j);
if (titleRow.get(j) != null) {
otherRowCell.setCellValue(j+"");
} else {
otherRowCell.setCellValue("");
}
}
String fileName="文件名称";
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
if(null == fileName || "".equals(fileName))
response.setHeader("Content-Disposition", "attachment;filename=" + createFileName("xlsx"));
else
response.setHeader("Content-disposition", "attachment;filename=" + fileName + " .xlsx");
ServletOutputStream outputStream = null;
try {
outputStream = response.getOutputStream();
workbook.write(outputStream);
} catch (Exception e) {
e.printStackTrace();
} finally {
workbook.close();
outputStream.close();
}