1. 程式人生 > >java匯出excel資料量過大解決方案

java匯出excel資料量過大解決方案

 @RequestMapping("/export")
public void export(HttpServletRequest request, HttpServletResponse response, FullProcess fullProcess) {
    // 檔名獲取
Date date = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
String f = "全流程報表-" + format.format(date);
    this.fileName = f;
setResponseHeader(response);
OutputStream out = null; try { out = response.getOutputStream(); List<FullProcess> list = fullProcessService.exportReceiveFullProcess(fullProcess); toExcel(list, request, 10000, f, out); } catch (IOException e1) { e1.printStackTrace(); } catch (Exception e) { e.printStackTrace();
} finally { try { out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } }

}

/**
 * 生成excel
 * @param list
* @param request
* @param length
* @param f
* @param out
* @throws IOException
 */
public void toExcel(List<FullProcess> list, HttpServletRequest request,
int length, String f, OutputStream out) throws IOException { List<String> fileNames = new ArrayList(); // 用於存放生成的檔名稱s String path = Env.getProperty(Env.FILE_UPLOAD_URL); File zip = new File(path + "excel/" + f + ".zip"); // 壓縮檔案 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss"); // 生成excel for (int j = 0, n = list.size() / length + 1; j < n; j++) { Workbook book = new HSSFWorkbook(); Sheet sheet = book.createSheet("全流程報表"); // double d = 0; // 用來統計 String file = path + "excel/" + f + "-" + j + ".xls"; fileNames.add(file); FileOutputStream o = null; try { o = new FileOutputStream(file); // sheet.addMergedRegion(new // CellRangeAddress(list.size()+1,0,list.size()+5,6)); Row row = sheet.createRow(0); row.createCell(0).setCellValue("需求單據號"); row.createCell(1).setCellValue("需求人"); row.createCell(2).setCellValue("需求日期"); row.createCell(3).setCellValue("需求部門"); row.createCell(4).setCellValue("是否有立項報告"); row.createCell(5).setCellValue("專案名稱"); row.createCell(6).setCellValue("立項金額"); row.createCell(7).setCellValue("收益核算方式"); row.createCell(8).setCellValue("年收益金額"); row.createCell(9).setCellValue("投資回收期"); row.createCell(10).setCellValue("專案類別"); row.createCell(11).setCellValue("需求數量"); row.createCell(12).setCellValue("需求金額"); row.createCell(13).setCellValue("需求審批狀態"); row.createCell(14).setCellValue("採購申請單號"); row.createCell(15).setCellValue("採購申請人"); row.createCell(16).setCellValue("採購申請日期"); row.createCell(17).setCellValue("採購申請數量"); row.createCell(18).setCellValue("採購申請金額"); row.createCell(19).setCellValue("採購申請審批狀態"); row.createCell(20).setCellValue("訂單單據號"); row.createCell(21).setCellValue("SAP訂單號"); row.createCell(22).setCellValue("供應商"); row.createCell(23).setCellValue("幣種"); row.createCell(24).setCellValue("稅率"); row.createCell(25).setCellValue("訂單申請人"); row.createCell(26).setCellValue("訂單申請日期"); row.createCell(27).setCellValue("訂單數量"); row.createCell(28).setCellValue("訂單金額"); row.createCell(29).setCellValue("訂單審批狀態"); row.createCell(30).setCellValue("收貨單據號"); row.createCell(31).setCellValue("收貨數量"); row.createCell(32).setCellValue("收貨日期"); row.createCell(33).setCellValue("驗收單號"); row.createCell(34).setCellValue("驗收數量"); row.createCell(35).setCellValue("驗收狀態"); row.createCell(36).setCellValue("驗收日期"); row.createCell(37).setCellValue("驗收人"); row.createCell(38).setCellValue("物料憑證號"); int m = 1; for (int i = 1, min = (list.size() - j * length + 1) > (length + 1) ? (length + 1) : (list.size() - j * length + 1); i < min; i++) { m++; FullProcess user = list.get(length * j + i - 1); //Double dd = user.getMoney(); /*if (dd == null) { dd = 0.0; } d += dd;*/ Row row1 = sheet.createRow(i); row1.createCell(0).setCellValue(user.getDoId() == null ? "" : user.getDoId().toString()); row1.createCell(1).setCellValue(user.getDoApplyUser() == null ? "" : user.getDoApplyUser()); row1.createCell(2).setCellValue(user.getDoApplyDate() == null ? "" : sdf.format(user.getDoApplyDate())); row1.createCell(3).setCellValue(user.getDoApplyDepartment() == null ? "" : user.getDoApplyDepartment()); row1.createCell(4).setCellValue(user.getProjectProposal() == null ? "" : user.getProjectProposal()); row1.createCell(5).setCellValue(user.getEntryName() == null ? "" : user.getEntryName()); row1.createCell(6).setCellValue(user.getProjectMoney() == null ? "" : user.getProjectMoney().toString()); row1.createCell(7).setCellValue(user.getIncomeAccountingMethod() == null ? "" : user.getIncomeAccountingMethod()); row1.createCell(8).setCellValue(user.getAnnualIncomeAmount() == null ? "" : user.getAnnualIncomeAmount().toString()); row1.createCell(9).setCellValue(user.getPaybackPeriodOfInvestment() == null ? "" : user.getPaybackPeriodOfInvestment()); row1.createCell(10).setCellValue(user.getProjectType() == null ? "" : user.getProjectType()); row1.createCell(11).setCellValue(user.getDoDemandCount() == null ? "" : user.getDoDemandCount().toString()); row1.createCell(12).setCellValue(user.getDoIamoney() == null ? "" : user.getDoIamoney().toString()); row1.createCell(13).setCellValue(user.getDoCapprovalstate() == null ? "" : user.getDoCapprovalstate()); row1.createCell(14).setCellValue(user.getAoId() == null ? "" : user.getAoId()); row1.createCell(15).setCellValue(user.getAoApplyUser() == null ? "" : user.getAoApplyUser()); row1.createCell(16).setCellValue(user.getAoApplyDate() == null ? "" : sdf.format(user.getAoApplyDate())); row1.createCell(17).setCellValue(user.getApApplyCount() == null ? "" : user.getApApplyCount().toString()); row1.createCell(18).setCellValue(user.getAoIamoney() == null ? "" : user.getAoIamoney().toString()); row1.createCell(19).setCellValue(user.getAoCapprovalstate() == null ? "" : user.getAoCapprovalstate()); row1.createCell(20).setCellValue(user.getPurchaseOrderId() == null ? "" : user.getPurchaseOrderId()); row1.createCell(21).setCellValue(user.getPurchaseOrderSapId() == null ? "" : user.getPurchaseOrderSapId()); row1.createCell(22).setCellValue(user.getSupplierName() == null ? "" : user.getSupplierName()); row1.createCell(23).setCellValue(user.getCurrencyName() == null ? "" : user.getCurrencyName()); row1.createCell(24).setCellValue(user.getTaxRate() == null ? "" : user.getTaxRate()); row1.createCell(25).setCellValue(user.getPoApplyUser() == null ? "" : user.getPoApplyUser()); row1.createCell(26).setCellValue(user.getPoApplyDate() == null ? "" : sdf.format(user.getPoApplyDate())); row1.createCell(27).setCellValue(user.getPoApplyCount() == null ? "" : user.getPoApplyCount().toString()); row1.createCell(28).setCellValue(user.getPoIamoney() == null ? "" : user.getPoIamoney().toString()); row1.createCell(29).setCellValue(user.getPoCapprovalstate() == null ? "" : user.getPoCapprovalstate()); row1.createCell(30).setCellValue(user.getReceiveGoodsId() == null ? "" : user.getReceiveGoodsId()); row1.createCell(31).setCellValue(user.getReceiveDate() == null ? "" : sdf.format(user.getReceiveDate())); row1.createCell(32).setCellValue(user.getReceiveGoodsCount() == null ? "" : user.getReceiveGoodsCount().toString()); row1.createCell(33).setCellValue(user.getCheckAcceptId() == null ? "" : user.getCheckAcceptId()); row1.createCell(34).setCellValue(user.getCheckCount() == null ? "" : user.getCheckCount().toString()); row1.createCell(35).setCellValue(user.getCaCapprovalstate() == null ? "" : user.getCaCapprovalstate()); row1.createCell(36).setCellValue(user.getCaCheckDate() == null ? "" : sdf.format(user.getCaCheckDate())); row1.createCell(37).setCellValue(user.getApplyCheckUserName() == null ? "" : user.getApplyCheckUserName()); row1.createCell(38).setCellValue(user.getEpMaterialdocument() == null ? "" : user.getEpMaterialdocument()); } /* CellStyle cellStyle2 = book.createCellStyle(); cellStyle2.setAlignment(CellStyle.ALIGN_CENTER); row = sheet.createRow(m); Cell cell0 = row.createCell(0); cell0.setCellValue("Total"); cell0.setCellStyle(cellStyle2); Cell cell4 = row.createCell(4); cell4.setCellValue(d); cell4.setCellStyle(cellStyle2); sheet.addMergedRegion(new CellRangeAddress(m, m, 0, 3));*/ } catch (Exception e) { e.printStackTrace(); } try { book.write(o); } catch (Exception ex) { ex.printStackTrace(); } finally { o.flush(); o.close(); } } File []srcfile = new File[fileNames.size()]; for (int i = 0, n = fileNames.size(); i < n; i++) { srcfile[i] = new File(fileNames.get(i)); } zipFiles(srcfile, zip); FileInputStream inStream = new FileInputStream(zip); byte[] buf = new byte[4096]; int readLength; while ((readLength = inStream.read(buf)) != -1) { out.write(buf, 0, readLength); } inStream.close(); deleteFile(fileNames, path + "excel/" + f + ".zip"); }
/**
 * 檔案刪除
 * @param fileNames
* @param zipPath
*/
public void deleteFile(List<String> fileNames, String zipPath) {
    String sPath = null;
File file = null;
    boolean flag = false;
    try {
        // 判斷目錄或檔案是否存在
for (int i = 0; i < fileNames.size(); i++) {
            sPath = fileNames.get(i);
file = new File(sPath);
            if (file.exists())  {
                file.delete();
}
        }
        file = new File(zipPath);
        if (file.exists())  {
            file.delete();
}
    } catch (Exception e) {
        e.printStackTrace();
}
}
/**
 *
 * @param srcfile 檔名陣列
 * @param zipfile 壓縮後文件
 */
public static void zipFiles(java.io.File[] srcfile, java.io.File zipfile) {
    byte[] buf = new byte[1024];
    try {
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
                zipfile));
        for (int i = 0; i < srcfile.length; i++) {
            FileInputStream in = new FileInputStream(srcfile[i]);
out.putNextEntry(new ZipEntry(srcfile[i].getName()));
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
}
            out.closeEntry();
in.close();
}
        out.close();
} catch (IOException e) {
        e.printStackTrace();
}
}
/**
 * 設定響應頭
 */
public void setResponseHeader(HttpServletResponse response) {
    try {
        response.setContentType("application/octet-stream;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment;filename="
+ java.net.URLEncoder.encode(this.fileName, "UTF-8")
                + ".zip");
response.addHeader("Pargam", "no-cache");
response.addHeader("Cache-Control", "no-cache");
} catch (Exception ex) {
        LOGGER.error("e", ex);
}
}