将网格数据导出到Excel并以zip格式保存

时间:2014-02-28 16:25:26

标签: c# asp.net gridview zip export-to-excel

您好我正在研究asp网络应用程序。在这里我需要将网格数据导出到Excel,最后excel文件应该保存为zip文件。我不想先在某个位置保存Excel文件,然后使用zip功能获取该文件并将其转换为Zip并保存。我想要的功能将直接将网格转换为Excel然后Zip然后最终保存它。我见过很多表格和网站,但都没有给出正确答案。

1 个答案:

答案 0 :(得分:1)

您可以通过dot.net Zip dll执行此操作。以下代码可以帮助您

gv.AllowPaging = false;
            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment; filename=" + strFileName);
            Response.ContentType = "application/zip";
            System.IO.StringWriter sw = new System.IO.StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            gv.RenderControl(htw);
           // byte[] toBytes = Encoding.ASCII.GetBytes(somestring);
            MemoryStream stream = new MemoryStream();
             string attachment = sw.ToString();
             byte[] data = Encoding.ASCII.GetBytes(attachment);
                stream.Write(data, 0, data.Length);
                stream.Seek(0, SeekOrigin.Begin);   // <-- must do this after writing the stream!
           //   File.WriteAllBytes(@"D:\Saurabh\Testing\inputpdf\saurabhhtest.xls", stream.GetBuffer());



        using (ZipFile zipFile = new ZipFile())
        {
            zipFile.AddEntry("saurabhtest1.xls", stream);
            zipFile.Save(Response.OutputStream);
        }