繁体   English   中英

在使用Open XML下载之前,如何压缩Excel文件?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM