/**
* 導出Excel
* @author Saffi
*/
@RequestMapping("exportExcel.action")
public void exportExcel(HttpServletResponse response) throws IOException {
try {
// 查詢並賦給List集合
List<Entity> oddList = entityService.listExport();
// 在內存中創建一個Excel文件,通過輸出流寫到客戶端提供下載
// 內存中保留 10000 條數據,以免內存溢出,其余寫入 硬盤
SXSSFWorkbook workbook = new SXSSFWorkbook(10000);
// 創建一個sheet頁
SXSSFSheet sheet = (SXSSFSheet) workbook.createSheet("這是sheet名");
// 分別設置Excel列的寬度
sheet.setColumnWidth(0, 100 * 40);
sheet.setColumnWidth(1, 100 * 50);
sheet.setColumnWidth(2, 100 * 50);
// 創建標題
SXSSFRow headRow = (SXSSFRow) sheet.createRow(0);
headRow.createCell(0).setCellValue("編號");
headRow.createCell(1).setCellValue("時間");
headRow.createCell(2).setCellValue("單號");
// 遍歷oddList集合
for (OddNunber odd : oddList) {
// 創建行
SXSSFRow dataRow = (SXSSFRow) sheet.createRow(sheet.getLastRowNum() + 1);
// 創建下標為0的Cell,並將其值設為查詢結果中的編號
dataRow.createCell(0).setCellValue(odd.getOnid());
// 創建下標為1的Cell,並將其值設為查詢結果中的日期
dataRow.createCell(1).setCellValue(odd.getOrecorddate());
// 創建下標為2的Cell,並將其值設為查詢結果中的單號
dataRow.createCell(2).setCellValue(odd.getCustomernumber());
}
// 設置生成的Excel的文件名,並以中文進行編碼
String codedFileName = new String("Excel名".getBytes("gbk"), "iso-8859-1");
response.setHeader("Content-Disposition", "attachment;filename=" + codedFileName + ".xlsx");
// 響應類型,編碼
response.setContentType("application/octet-stream;charset=UTF-8");
// 形成輸出流
OutputStream osOut = response.getOutputStream();
// 將指定的字節寫入此輸出流
workbook.write(osOut);
// 刷新此輸出流並強制將所有緩沖的輸出字節被寫出
osOut.flush();
// 關閉流
osOut.close();
/*
* dispose of temporary files backing this workbook on disk 處理在磁盤上備份此工作簿的臨時文件
* SXSSF分配臨時文件,您必須始終清除顯式,通過調用dispose方法
*/
workbook.dispose();
} catch (Exception e) {
e.printStackTrace();
response.sendRedirect("error.action");
log.error("系統錯誤", e.fillInStackTrace());
}
}