In this article I will explain how to save ASP.Net GridView control to server’s disk as Microsoft Excel Spreadsheet using ASP.Net.
In the below HTML Markup I have a simple ASP.Net GridView Control and an ASP.Net Button for saving the GridView to Excel sheet on server’s disk.
You will need to import the following namespaces for this sample tow work.
Binding the GridView
In the below code snippet I am binding the ASP.Net GridView control with a datatable.
Saving the ASP.Net GridView as Excel Spreadsheet on Server’s Disk
Once the GridView is bind with data we will now write the code to save it as Excel file on the server’s disk. Hence on the Click event handler of the Save button I have written the following code.
Above I am first checking whether the Directory where the excel needs to be saved exists, if not I create it and then I render the GridView as HTML and then save it to disk using StreamWriter class.
While exporting you might get the following error
Hence to resolve it you need to refer Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server.
You can download the source code in VB.Net and C# using the download link provided below.SaveGridViewAsExcelOnDisk.zip