Search code examples
c#asp.netgridviewzipexport-to-excel

Exporting Grid Data to Excel and saving it in zip format


Hi i'm working on asp net application. In this I need to Export Grid data to Excel and finally the excel file should be saved as zip file. I don't want to first save Excel file in some location then use zip functionality to fetch that file and convert it into Zip and save it. I want functionality which will directly convert Grid to Excel then Zip then finally saves it. I've seen so many forms and sites but none gave proper answer.


Solution

  • You can do this by dot.net Zip dll And following code will help you

    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);
            }