Click here to Skip to main content
15,905,316 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi members,

How do I export 2 gridviews (GridView1 & GridView2) into 2 seperated sheets in 1 ms-excel file? Currently, I'm able to export only 1 gridview to an excelsheet which the filename is the same as the sheet name. But I would like to 2 gridviews into 2 seperated sheets which I would like sheet name to be define/set by myself. thanks.
C#
    public void ExportGridToExcel()
{
    Response.Clear();
    Response.Buffer = true;
    Response.ClearContent();
    Response.ClearHeaders();
    Response.Charset = "";
    string FileName ="Export"+DateTime.Now+".xls";
    StringWriter strwritter = new StringWriter();
    HtmlTextWriter htmltextwrtter = new HtmlTextWriter(strwritter);
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.ContentType = "application/vnd.ms-excel";
    Response.AddHeader("Content-Disposition","attachment;filename=" + FileName);
    GridView1.GridLines = GridLines.Both;
    GridView1.HeaderStyle.Font.Bold = true;
    GridView1.RenderControl(htmltextwrtter);
    Response.Write(strwritter.ToString());
    Response.End();
}

    public override void VerifyRenderingInServerForm(Control control)
    {
        return;
    }
Posted
Comments
Livalwas 15-Oct-15 4:32am    
Take a look at this article. It shows how to create a workbook from the GridView control. Now what you'll need to do is create two workbooks (one for each GridView) and then add the worksheet from the second one into a first one, something like the following:

excel1.Worksheets.AddCopy("Sheet2", excel2.Worksheets[0]);

Note that this article uses this C# library for excel's workbooks.

1 solution

You can add sheets if you use Interop or OpenXML.

Also have a look here - Export DataSet to Multiple Excel Sheets[^]
 
Share this answer
 
Comments
waynetan123 28-Sep-15 5:29am    
Hi, how can I do so with gridview? lets say I got gridview1 and gridview2.thanks
You can get GridView data in a DataTable. The example in the link is shown for two DataTables. Have a look and try to implement.
waynetan123 29-Sep-15 3:33am    
Do I need to add any references because once I added I receive 290 errors
What type of errors?
waynetan123 30-Sep-15 2:51am    
It underlines most of the codes

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900