Click here to Skip to main content
15,898,134 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have two Gridviews. GridView1 and GridView2 on one page. However, i want to export both gridviews into an excel having Gridview1 on one tab and GridView2 on another tab. Is that possible with the code that i have implemented below?
Is it possible to add another tab to the excel for GridView2?

VB.NET
Protected Sub ExportAsExcel_Click(sender As Object, e As EventArgs) Handles ExportAsExcel.ClickResponse.Clear()
        Response.Buffer = True
        Response.AddHeader("content-disposition", "attachment;filename=Export.xls")
        Response.Charset = ""
            Response.ContentType = "application/vnd.ms-excel"
            Using sw As New StringWriter()
                Dim hw As New HtmlTextWriter(sw)
                GridView1.RenderControl(hw)
                
                Dim style As String = ""
                Response.Write(style)
                Response.Output.Write(sw.ToString())
                Response.Flush()
                Response.End()
            End Using

    End Sub


What I have tried:

Google was no help. I even tried to add GridView 2 to the code but i am logically stuck in this matter.
Posted
Updated 12-Oct-16 7:58am
v2

1 solution

With current approach its not possible, instead get your two gridview data into two different datatable and using OpenXML SDK export it

Refer Export DataSet DataTables to multiple Excel Sheets (Worksheets) in ASP.Net using C# and VB.Net[^]

Export to Excel – Multiple GridView into Multiple Worksheet[^]
 
Share this answer
 
v3
Comments
JT1992 12-Oct-16 14:43pm    
so there is absolutely no way to add another gridview to another tab using my code above?
Diecte 13-Oct-16 6:49am    
Yes, there is no way to achieve that with your approach.
You see that does not actually create an Excel file, but rather a HTML file which has an ".xls" extension.
Take a look at your "sw.ToString()" value, you'll notice that it's a string that contains a HTML table.
Now why this "trick" is commonly used is because MS Excel is able to read HTML files so it will be able to open that file as well, however it will pomp you a warning saying that the file's format and extension are not the same.

Nevertheless is short that is HTML file and you cannot define multiple sheets with it, you'll need to write a real Excel file with VB.NET to achieve that, for example take a look at this sample.
manu_dhobale 12-Oct-16 16:03pm    
I found one article, you can try it, check second link from updated solution

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