[英]How to zip Excel file before it is downloading using Open XML?
我正在使用下面的代碼創建,它將向用戶顯示用戶提示,用戶是否可以保存或打開或取消Excel文件。
我可以成功下載文件,但需要先壓縮才能顯示用戶提示,以后會像打開選項,保存或取消選項一樣向用戶顯示zip文件。
不使用任何其他第三方庫並使用Microsoft自己的Gzip DLL怎么辦?
以下代碼用於導出到excel功能:
public ActionResult ExportToExcel()
{
byte[] file;
string targetFilename = string.Format("{0}-{1}.xlsx", "Generated", "excel");
DataTable dt = common.CreateExcelFile.ListToDataTable(GetSearchDraftPRResults());
common.CreateExcelFile excelFileForExport = new CreateExcelFile();
file = excelFileForExport.CreateExcelDocumentAsStream(dt, targetFilename);
Response.Buffer = true;
return File(file, "application/vnd.ms-excel", targetFilename);
}
在將文件顯示給用戶之前,誰能幫忙壓縮文件嗎?
提前謝謝了.....
修改后的代碼:
public ActionResult ExportToExcel()
{
byte[] file;
string targetFilename = string.Format("{0}-{1}.xlsx", "Generated", "excel");
DataTable dt = common.CreateExcelFile.ListToDataTable(GetSearchDraftPRResults());
common.CreateExcelFile excelFileForExport = new CreateExcelFile();
file = excelFileForExport.CreateExcelDocumentAsStream(dt, targetFilename);
Response.Buffer = true;
byte[] zipFile = Compress(file);
return File(file, "application/vnd.ms-excel", targetFilename);
}
public byte[] Compress(FileInfo fileToCompress)
{
using (FileStream originalFileStream = fileToCompress.OpenRead())
{
if ((System.IO.File.GetAttributes(fileToCompress.FullName) & FileAttributes.Hidden) != FileAttributes.Hidden & fileToCompress.Extension != ".gz")
{
using (FileStream compressedFileStream = System.IO.File.Create(fileToCompress.FullName + ".gz"))
{
using (GZipStream compressionStream = new GZipStream(compressedFileStream, CompressionMode.Compress))
{
originalFileStream.CopyTo(compressionStream);
}
}
}
MemoryStream mem = new MemoryStream();
CopyStream(originalFileStream, mem);
return mem.ToArray();
}
}
public static void CopyStream(Stream input, Stream output)
{
byte[] b = new byte[32768];
int r;
while ((r = input.Read(b, 0, b.Length)) > 0)
output.Write(b, 0, r);
}
查看SharpZipLib庫 。 它效果很好,即使在商業應用中也可以免費使用。
您可以從JCraft使用JZlib。 壓縮聲明非常易於使用,看起來像這樣,其中的代碼取決於您在做什么,但是您可以在JZlib示例中找到有效的示例:
public byte[] compress(byte[] buf, int start, int[] len) {
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.