即时创建和压缩Excel文件

时间:2014-06-13 09:22:00

标签: c# asp.net .net asp.net-mvc sharpziplib

我正在尝试压缩Excel文件,并在提示中向用户显示生成的压缩文件,并提供保存,打开和取消选项。

我使用 sharpZip .Net Library 压缩Excel文件,当您点击Export to excel的链接时,用户提示无法显示。

代码如下。我在这个方法中得到了一个 SingleGZip(file); ,它说该方法有一些无效的参数。

    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;

       SingleGZip(file);
        //Stream memStream = new MemoryStream(file);

        //using (ZipFile zipFile = new ZipFile())
        //{
        //    zipFile.AddEntry("Generated-Excel.xlsx", "", memStream);
        //    Response.ClearContent();
        //    Response.ClearHeaders();
        //    Response.AppendHeader("content-disposition", "attachment; filename=Report.zip");

        //    zipFile.Save(Response.OutputStream);
        //}
        //return 

        //byte[] zipFile = Compress(file);
        return File(file, "application/vnd.ms-excel", targetFilename);          
    }

    private byte[] SingleGZip(string source)
    {
        string target = source + ".gz";

        using (Stream s = new GZipOutputStream(System.IO.File.Create(target)))
        {
            using (FileStream fs = System.IO.File.OpenRead(source))
            {
                byte[] buffer = new byte[fs.Length];
                fs.Read(buffer, 0, (int)fs.Length);
                s.Write(buffer, 0, buffer.Length);
            }

        }

    }

1 个答案:

答案 0 :(得分:0)

private byte[] SingleGZip(string source) <-- give me a string

期望字符串作为参数,并且您在控制器中将字节数组传递给SigleZip方法。

byte[] file; <-- array of bytes
        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;

       SingleGZip(file); <-- array of bytes