In this article we will learn how to export data directly from sql server database table to excel,
below is the database table which contain some data
I will export this data into excel file to excel by using C#.net coding as below:
1.Add a new file TabletoExcel.aspx in the solution explorer
Copy and paste below code in TabletoExcel.aspx page
| 
01 
02 
03 
04 
05 
06 
07 
08 
09 
10 
11 
12 
13 | <body><formid="form1"runat="server"><div><asp:ButtonID="btnGenaerateToExcel"runat="server"onclick="btnGenerateToExcel_Click"Text="Button"/></div></form></body> | 
Copy and paste below code in TabletoExcel.cs  page:
| 
01 
02 
03 
04 
05 
06 
07 
08 
09 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
29 
30 
31 
32 
33 
34 
35 
36 
37 
38 
39 
40 
41 
42 
43 
44 
45 
46 
47 
48 
49 
50 
51 
52 
53 
54 
55 
56 
57 
58 
59 
60 
61 
62 
63 
64 
65 
66 
67 
68 
69 
70 
71 
72 
73 
74 
75 
76 | usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Web;usingSystem.Web.UI;usingSystem.Web.UI.WebControls;usingSystem.Configuration;usingSystem.Data.SqlClient;usingSystem.Data;publicpartialclassTableToExcel : System.Web.UI.Page{protectedvoidPage_Load(objectsender, EventArgs e){}protectedvoidbtnGenerateToExcel_Click(objectsender, EventArgs e){PopulatExcelEntry();}protectedvoidPopulatExcelEntry(){SqlConnection Connection = newSqlConnection("Server=Munesh-PC;Database=Griddata;Uid=sa;Pwd=123");DataSet ds = newDataSet();SqlDataAdapter adapter = newSqlDataAdapter("select * from Tbl_Mst_Employee", Connection);try{adapter.Fill(ds);ExportToExcel(ds);}catch(Exception ex){Connection.Close();}}publicstaticvoidExportToExcel(System.ComponentModel.MarshalByValueComponent DataSource){try{System.IO.StringWriter objStringWriter = newSystem.IO.StringWriter();System.Web.UI.WebControls.DataGrid tempDataGrid = newSystem.Web.UI.WebControls.DataGrid();System.Web.UI.HtmlTextWriter objHtmlTextWriter = newSystem.Web.UI.HtmlTextWriter(objStringWriter);HttpContext.Current.Response.ClearContent();HttpContext.Current.Response.ClearHeaders();HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";HttpContext.Current.Response.Charset = "";HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=TableToExcel.xls");tempDataGrid.DataSource = DataSource;tempDataGrid.DataBind();tempDataGrid.HeaderStyle.Font.Bold = true;tempDataGrid.RenderControl(objHtmlTextWriter);DataSource.Dispose();HttpContext.Current.Response.Write(objStringWriter.ToString());HttpContext.Current.Response.End();HttpContext.Current.ApplicationInstance.CompleteRequest();}catch(Exception ex){throwex;}}} | 
Run you application and click on button
Click on Ok and you will get your required output as:
