一.大數據量的導出:java
採用分頁的思想,分多個sheet。數據庫
public ResponseEntity exportBigDataExcel() throws Exception { try { int pageSize = 100000; SXSSFWorkbook wb = new SXSSFWorkbook(100000); Sheet sheet = null; // 工做表對象 Row nRow = null; // 行對象 Cell nCell = null; // 獲取數據庫中行數 Integer dataCount = activityDataMapper.selectDataCount(); // 根據函數,獲取提取次數 int exportTimes = dataCount % pageSize > 0 ? dataCount / pageSize + 1 : dataCount / pageSize; // 按次數將數據寫入文件 for (int i = 0; i < exportTimes; i++) { sheet = wb.createSheet("百萬英雄00" + i + "的sheet"); sheet = wb.getSheetAt(i); // 第一行 nRow = sheet.createRow(0); nCell = nRow.createCell(0); nCell.setCellValue("ID"); nCell = nRow.createCell(1); nCell.setCellValue("用戶id"); nCell = nRow.createCell(2); nCell.setCellValue("頁面id"); nCell = nRow.createCell(3); nCell.setCellValue("點擊時間"); int pageNo = i * pageSize; List<ActivityData> activityDataList = activityDataMapper.selectActivityDataByPage(pageNo, pageSize); for (int j = 0; j < activityDataList.size(); j++) { // 100000一個sheet Row dataRow = sheet.createRow(j + 1); nCell = dataRow.createCell(0); nCell.setCellValue(activityDataList.get(j).getId().toString()); nCell = dataRow.createCell(1); nCell.setCellValue(activityDataList.get(j).getAid().toString()); nCell = dataRow.createCell(2); nCell.setCellValue(activityDataList.get(j).getPageId().toString()); nCell = dataRow.createCell(3); nCell.setCellValue(DateUtil.dateToStr(activityDataList.get(j).getCreateD(), DateUtil.TIME_PATTERN)); } } String fileName = "活動數據明細.xlsx"; return ExcelUtil.outputExcel(wb, fileName); } catch (Exception e) { LoggerUtil.error("ActivityDataService exportBigDataExcel Exception" + e.getMessage(), e); throw e; } }
public static ResponseEntity outputExcel(Workbook workbook, String fileName) throws Exception { //將excel寫入流中 ByteArrayOutputStream byteArrayOutputStream = null; try { byteArrayOutputStream = new ByteArrayOutputStream(); workbook.write(byteArrayOutputStream); HttpHeaders headers = new HttpHeaders(); headers.add("Cache-Control", "no-cache, no-store, must-revalidate"); headers.add("Pragma", "no-cache"); headers.add("Expires", "0"); headers.add("charset","utf-8"); //文件名 fileName= URLEncoder.encode(fileName, "UTF-8"); headers.add("fileName",fileName); InputStreamResource resource = new InputStreamResource(new ByteArrayInputStream(byteArrayOutputStream.toByteArray() )); return ResponseEntity.ok() .headers(headers) .contentType(MediaType.parseMediaType("application/octet-stream")) .body(resource); } catch (Exception e) { return null; }finally { if (null != byteArrayOutputStream) { byteArrayOutputStream.close(); } if (null != workbook) { workbook.close(); } } }