Introduction :
Hi, here i will code you how to Create and Download the Excel sheet using C# and Asp.net the Data of Excel sheet will be loaded from Database.
Logic :
Here i have created a Dummy Gridview, values from the Database will bind into the dummy Grid, and later Create the Excel sheet and Write Grid Data to the Excel and Render it.
Aspx code :
Code behind (C#) :
Hi, here i will code you how to Create and Download the Excel sheet using C# and Asp.net the Data of Excel sheet will be loaded from Database.
Logic :
Here i have created a Dummy Gridview, values from the Database will bind into the dummy Grid, and later Create the Excel sheet and Write Grid Data to the Excel and Render it.
Aspx code :
<html>
<head runat="server">
<title>Fourthbottle</title>
</head>
<body style="text-align:center">
<form id="form1" runat="server">
Click to Create and Download Excel,Excel Data from
DB.
<div>
<asp:Button ID="btnClick" runat="server" Text="Create" onclick="btnClick_Click" />
</div>
</form>
</body>
</html>
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Text;
namespace DBTOEXCEL
{
public partial class Page1 :
System.Web.UI.Page
{
SqlConnection con = new
SqlConnection("your
Conn String");
protected void
btnClick_Click(object sender, EventArgs e)
{
DataTable dt = new
DataTable();
SqlDataAdapter da = new
SqlDataAdapter("select
* from table1", con);
con.Open();
da.Fill(dt);
con.Close();
GridView gv = new
GridView();
gv.DataSource = dt;
gv.DataBind();
Response.Clear();
Response.AddHeader("content-disposition","attachment;filename=ExcelDownload.xls");
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new
StringWriter();
HtmlTextWriter hw = new
HtmlTextWriter(sw);
gv.RenderControl(hw);
Response.Output.Write(sw.ToString());
Response.End();
}
}
}