<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm3.aspx.cs" Inherits="布局.WebForm3" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:Button ID ="btnExport" runat ="server" Text ="導出" onclick="btnExport_Click" /> </div> </form> </body> </html>
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.IO; namespace 布局 { public partial class WebForm3 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnExport_Click(object sender, EventArgs e) { try { List<FileInfo> fileList = new List<FileInfo>(); string fileName1 = @"D:\Export\新建 Microsoft Office Excel 工作表1.xlsx"; string fileName2 = @"D:\Export\新建 Microsoft Office Excel 工作表2.xlsx"; fileList.Add(new FileInfo(fileName1)); fileList.Add(new FileInfo(fileName2)); string fileName = "Export_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".zip"; //調用方法 string targetZipFilePath =Server.MapPath("/")+ "Export\\" + fileName;// 擴展名可隨意 //壓縮csv文件 FileCompression.Compress(fileList, targetZipFilePath, 5, 5); //把壓縮文件輸出到瀏覽器 System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response; Response.Clear(); Response.ContentType = "application/zip"; Response.AddHeader("Content-Disposition", "attachment; FileName=" + HttpUtility.UrlEncode(fileName)); Response.BinaryWrite(File2Bytes(targetZipFilePath)); Response.OutputStream.Flush(); Response.OutputStream.Close(); Response.End();//這句代碼不能少,否則可能導致輸出的文件數據不全,導致解壓時出現壓縮格式未知的錯誤 //刪除產生的壓縮文件 try { FileInfo fi1 = new FileInfo(targetZipFilePath); fi1.Delete(); } catch (Exception ex) { } } catch (Exception ex) { ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "CreateExcelErrorTip", "alert('Export Failed!');", true); return; } } public static byte[] File2Bytes(string path) { if (!System.IO.File.Exists(path)) { return new byte[0]; } FileInfo fi = new FileInfo(path); byte[] buff = new byte[fi.Length]; FileStream fs = fi.OpenRead(); fs.Read(buff, 0, Convert.ToInt32(fs.Length)); fs.Close(); return buff; } } }
壓縮用到的
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.IO; using ICSharpCode.SharpZipLib.Zip; using System.Threading; namespace 布局 { public class FileCompression { public FileCompression() { // // TODO: 在此處添加構造函數邏輯 // } #region 加密、壓縮文件 /// <summary> /// 壓縮文件 /// </summary> /// <param name="fileNames">要打包的文件列表</param> /// <param name="GzipFileName">目標文件名</param> /// <param name="CompressionLevel">壓縮品質級別(0~9)</param> /// <param name="SleepTimer">休眠時間(單位毫秒)</param> public static void Compress(List<FileInfo> fileNames, string GzipFileName, int CompressionLevel, int SleepTimer) { ZipOutputStream s = new ZipOutputStream(File.Create(GzipFileName)); try { s.SetLevel(CompressionLevel); //0 - store only to 9 - means best compression foreach (FileInfo file in fileNames) { FileStream fs = null; try { fs = file.Open(FileMode.Open, FileAccess.ReadWrite); } catch { continue; } // 方法二,將文件分批讀入緩沖區 byte[] data = new byte[2048]; int size = 2048; ZipEntry entry = new ZipEntry(Path.GetFileName(file.Name)); entry.DateTime = (file.CreationTime > file.LastWriteTime ? file.LastWriteTime : file.CreationTime); s.PutNextEntry(entry); while (true) { size = fs.Read(data, 0, size); if (size <= 0) break; s.Write(data, 0, size); } fs.Close(); file.Delete(); Thread.Sleep(SleepTimer); } } finally { s.Finish(); s.Close(); } } #endregion #region 解密、解壓縮文件 /// <summary> /// 解壓縮文件 /// </summary> /// <param name="GzipFile">壓縮包文件名</param> /// <param name="targetPath">解壓縮目標路徑</param> public static void Decompress(string GzipFile, string targetPath) { //string directoryName = Path.GetDirectoryName(targetPath + "\\") + "\\"; string directoryName = targetPath; if (!Directory.Exists(directoryName)) Directory.CreateDirectory(directoryName);//生成解壓目錄 string CurrentDirectory = directoryName; byte[] data = new byte[2048]; int size = 2048; ZipEntry theEntry = null; using (ZipInputStream s = new ZipInputStream(File.OpenRead(GzipFile))) { while ((theEntry = s.GetNextEntry()) != null) { if (theEntry.IsDirectory) {// 該結點是目錄 if (!Directory.Exists(CurrentDirectory + theEntry.Name)) Directory.CreateDirectory(CurrentDirectory + theEntry.Name); } else { if (theEntry.Name != String.Empty) { //解壓文件到指定的目錄 using (FileStream streamWriter = File.Create(CurrentDirectory + theEntry.Name)) { while (true) { size = s.Read(data, 0, data.Length); if (size <= 0) break; streamWriter.Write(data, 0, size); } streamWriter.Close(); } } } } s.Close(); } } #endregion } }
