在開發過程中,數據導出excel的功能很常見,數據少,到沒問題,一旦超過65535條數據就會報錯,因此可以考慮導出多個sheet來解決,代碼如下:
private static void exportExcel() throws Exception { //總記錄數 int totalNum = 200000; //每個sheet設置60000 int avgNum = 60000; //建立新的sheet對象(excel的表單) //計算需要生成多少個sheet int sheetCount = (int) Math.ceil(Double.valueOf(totalNum) / Double.valueOf(avgNum)); File tempFile = new File("E:\\result5.xls"); FileOutputStream outputStream = new FileOutputStream(tempFile); //創建HSSFWorkbook對象(excel的文檔對象) HSSFWorkbook wb = new HSSFWorkbook(); for (int i = 0; i < sheetCount; i++) { HSSFSheet tempSheet = wb.createSheet("號段數據" + (i + 1)); HSSFRow tempRow = tempSheet.createRow(0); //創建單元格並設置單元格內容 tempRow.createCell(0).setCellValue("名稱"); tempRow.createCell(1).setCellValue("電話"); tempRow.createCell(2).setCellValue("是否有效"); tempRow.createCell(3).setCellValue("是否微信"); //在sheet里創建第三行 int startIndex = (i > 0 ? (i * avgNum) : 1); int endIndex = ((i + 1) * avgNum) > totalNum ? totalNum : ((i + 1) * avgNum); for (int j = startIndex; j <= totalNum; j++) { if (j < endIndex) { int rowIndex = (i > 0 ? (j - (i * avgNum)) + 1 : j); HSSFRow tempRow2 = tempSheet.createRow(rowIndex); tempRow2.createCell(0).setCellValue("test" + (j)); tempRow2.createCell(1).setCellValue("12312342312"); tempRow2.createCell(2).setCellValue("是"); tempRow2.createCell(3).setCellValue("是"); } } } wb.write(outputStream); outputStream.flush(); outputStream.close(); //以下是輸出Excel文件 }