Export SQL Data to Excel Using ASP.Net


This article explains how to export SQL Data to Excel using ASP.NET.
This article will help you to show the SQL data to the user and if he wishes then he can save that data in Excel Format.
Let's see the procedure required to create this type of application.
Step 1
First of all, I have worked on SQL where I have created a Stored Procedure named "same_city". This SP processes a table where records of various Branch Students exist. It will fetch the students of all branches in the same city.
Then I create a new project in ASP.NET and provide the connection of the Students Database to this application. This can be done by right-clicking on "Add Connection" in the Server Explorer and choose "Add New Connection".
sql to excel1
Step 2
After creating the connection with the Database I worked on the design page of the application and there used two buttons and a Grid View. The code of this page is as follows:
  1. <form id="form1" runat="server">  
  2.     <div>  
  3.         <asp:Button runat="server" Text="Fetch Data" OnClick="Unnamed1_Click" />  
  4.         <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Get Data" />  
  5.         <br />  
  6.         <br />  
  7.         <asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="3" GridLines="Vertical">  
  8.             <AlternatingRowStyle BackColor="#DCDCDC" />  
  9.             <FooterStyle BackColor="#CCCCCC" ForeColor="Black" />  
  10.             <HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />  
  11.             <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />  
  12.             <RowStyle BackColor="#EEEEEE" ForeColor="Black" />  
  13.             <SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />  
  14.             <SortedAscendingCellStyle BackColor="#F1F1F1" />  
  15.             <SortedAscendingHeaderStyle BackColor="#0000A9" />  
  16.             <SortedDescendingCellStyle BackColor="#CAC9C9" />  
  17.             <SortedDescendingHeaderStyle BackColor="#000065" />  
  18.         </asp:GridView>  
  19.     </div>  
  20. </form> 
The first button named "Fetch data" will be used to show the data in a Grid View and the second button will be used to download the shown data in Excel.
Step 3
Then I worked on the click of the first button, it's code is as follows:
  1. SqlConnection x;  
  2. SqlCommand y1;  
  3. DataTable dt;  
  4. protected void Unnamed1_Click(object sender, EventArgs e) {  
  5.     x = new SqlConnection(@ "Data Source=.;Initial Catalog=test;User ID=sa;Password=password@123");  
  6.     x.Open();  
  7.     y1 = new SqlCommand();  
  8.     y1.Connection = x;  
  9.     y1.CommandText = "same_city";  
  11.     y1.CommandType = CommandType.StoredProcedure;  
  13.     SqlDataAdapter y = new SqlDataAdapter(y1);  
  15.     dt = new DataTable();  
  16.     y.Fill(dt);  
  17.     GridView1.DataSource = dt;  
  18.     GridView1.DataBind();  
  19.     x.Close();  

Here first I created the connection with the database using SqlConnection, in the CommandText, I passed the name of Stored Procedure that is "same_city", I also provide the command type as StoredProcedure that will help to find what type of command is to be used.
Then the data is shown in the Grid.
Now if you run the application then you will be able to see the data from the SP but will not be able to download it in Excel format.
Step 4
Now our next task is to allow the user to save this data in Excel format; that is the main purpose of this application.
So, we will work on the click of the second button. Write this code with the click of the second button:
  1. if (GridView1.Visible) {  
  2.     Response.AddHeader("content-disposition""attachment; filename=GridViewToExcel.xls");  
  3.     Response.ContentType = "application/excel";  
  4.     StringWriter sWriter = new StringWriter();  
  5.     HtmlTextWriter hTextWriter = new HtmlTextWriter(sWriter);  
  6.     GridView1.RenderControl(hTextWriter);  
  7.     Response.Write(sWriter.ToString());  
  8.     Response.End();  

This code will first check whether some data is available in the Grid, if it's available then it will store that data with the name "GridViewToExcel".
But if you run your application you will get an error like:
Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server. 
This error will be removed by writing the following simple line of code:
  1. public override void VerifyRenderingInServerForm(Control control)  
  2. {  

Now your application is ready to be executed so you can debug it.
The complete code of my application is as follows:
  1. using System.Data;  
  2. using System.Data.SqlClient;  
  3. using System.Configuration;  
  4. using System.IO;  
  6. namespace WebApplication44 {  
  7.     public partial class WebForm1: System.Web.UI.Page {  
  8.         protected void Page_Load(object sender, EventArgs e) {  
  10.         }  
  11.         SqlConnection x;  
  12.         SqlCommand y1;  
  13.         DataTable dt;  
  14.         protected void Unnamed1_Click(object sender, EventArgs e) {  
  15.             x = new SqlConnection(@ "Data Source=.;Initial Catalog=test;User ID=sa;Password=password@123");  
  16.             x.Open();  
  17.             y1 = new SqlCommand();  
  18.             y1.Connection = x;  
  19.             y1.CommandText = "same_city";  
  21.             y1.CommandType = CommandType.StoredProcedure;  
  23.             SqlDataAdapter y = new SqlDataAdapter(y1);  
  25.             dt = new DataTable();  
  26.             y.Fill(dt);  
  27.             GridView1.DataSource = dt;  
  28.             GridView1.DataBind();  
  29.             x.Close();  
  30.         }  
  32.         protected void Button1_Click(object sender, EventArgs e) {  
  33.             if (GridView1.Visible) {  
  34.                 Response.AddHeader("content-disposition""attachment; filename=GridViewToExcel.xls");  
  35.                 Response.ContentType = "application/excel";  
  36.                 StringWriter sWriter = new StringWriter();  
  37.                 HtmlTextWriter hTextWriter = new HtmlTextWriter(sWriter);  
  38.                 GridView1.RenderControl(hTextWriter);  
  39.                 Response.Write(sWriter.ToString());  
  40.                 Response.End();  
  41.             }  
  42.         }  
  43.         public override void VerifyRenderingInServerForm(Control control) {}  
  44.     }  

On running the application you will get output like this:
sql to excel3
When you click on "Fetch Data" then you will see the data in Grid Format.
sql to excel2
Now if you click on the "Get Data" you will see that the data is stored in Excel format.
sql to excel4