將本地Excel文件壓縮為zip返回下載(解決壓縮文件名亂碼)
String zipPath =basePath+File.separator+"ZIP"+File.separator; File zip = new File(basePath+File.separator+"ZIP"+File.separator+fileName+Time+".zip"); filesToZip(srcfile, zip); response.setContentType("application/octet-stream"); response.setHeader("Location", zip.getName()); String fileName = new String(zip.getName().getBytes(StandardCharsets.UTF_8),StandardCharsets.ISO_8859_1); response.setHeader("Content-Disposition", "attachment; filename=" + fileName); try { OutputStream outputStream = response.getOutputStream(); InputStream inputStream = new FileInputStream(zip); byte[] buffer = new byte[1024]; int i = -1; while ((i = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, i); } inputStream.close(); } catch (Exception e) { e.printStackTrace(); } finally { delAllFile(zipPath); }
將日期段內的數據按模板生成Excel,存放于日期文件夾下即可,網上有很多生成Excel的代碼,這里略過
本地按日期生成的Excel,路徑分層 /日期/文件/ 前端訪問帶起始和結束時間,計算天數然后查回文件,將文件放集合再轉為File[],調用filesToZip來壓縮為一個壓縮包,返回給response的outputStream 即可
public void filesToZip(File[] srcFiles, File zipFile) { // 判斷壓縮后的文件存在不,不存在則創建 if (!zipFile.exists()) { try { zipFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } // 創建 FileOutputStream 對象 FileOutputStream fileOutputStream = null; // 創建 ZipOutputStream ZipOutputStream zipOutputStream = null; // 創建 FileInputStream 對象 FileInputStream fileInputStream = null; try { // 實例化 FileOutputStream 對象 fileOutputStream = new FileOutputStream(zipFile); // 實例化 ZipOutputStream 對象 zipOutputStream = new ZipOutputStream(fileOutputStream); // 創建 ZipEntry 對象 ZipEntry zipEntry = null; // 遍歷源文件數組 for (int i = 0; i < srcFiles.length; i++) { // 將源文件數組中的當前文件讀入 FileInputStream 流中 fileInputStream = new FileInputStream(srcFiles[i]); // 實例化 ZipEntry 對象,源文件數組中的當前文件 zipEntry = new ZipEntry(srcFiles[i].getName()); zipOutputStream.putNextEntry(zipEntry); // 該變量記錄每次真正讀的字節個數 int len; // 定義每次讀取的字節數組 byte[] buffer = new byte[1024]; while ((len = fileInputStream.read(buffer)) > 0) { zipOutputStream.write(buffer, 0, len); } } zipOutputStream.closeEntry(); zipOutputStream.close(); fileInputStream.close(); fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } }
最后將生成的臨時zip文件刪除
public static boolean delAllFile(String path) { boolean flag = false; File file = new File(path); if (!file.exists()) { return flag; } if (!file.isDirectory()) { return flag; } String[] tempList = file.list(); File temp = null; for (int i = 0; i < tempList.length; i++) { if (path.endsWith(File.separator)) { temp = new File(path + tempList[i]); } else { temp = new File(path + File.separator + tempList[i]); } if (temp.isFile()) { temp.delete(); } if (temp.isDirectory()) { delAllFile(path + "/" + tempList[i]);// 先刪除文件夾里面的文件 flag = true; } } return flag; }


當然,打包下載可以是日志文件等任何文件
學習時的痛苦是暫時的 未學到的痛苦是終生的
作者:卷心菜的奇妙歷險
本文版權歸作者和博客園共有,遵循 CC 4.0 BY-SA 版權協議,歡迎轉載 轉載請附上原文出處鏈接和本聲明,否則保留追究法律責任的權利。

浙公網安備 33010602011771號