Export to Excel code
aspx page :
<%@ Page Language="C#"
AutoEventWireup="true" CodeFile="Default2.aspx.cs"
Inherits="Default2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html
xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form
id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False" DataSourceID="SqlDataSource1"
DataKeyNames="Empid">
<Columns>
<asp:BoundField DataField="Empid"
HeaderText="Empid" SortExpression="Empid"
ReadOnly="True" />
<asp:BoundField DataField="Empname"
HeaderText="Empname"
SortExpression="Empname" />
<asp:BoundField DataField="Empsal"
HeaderText="Empsal"
SortExpression="Empsal" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1"
runat="server"
ConnectionString="<%$
ConnectionStrings:DBConnectionString %>"
SelectCommand="SELECT * FROM
[Table_1]"></asp:SqlDataSource>
<asp:Button ID="Button1"
runat="server" Text="Export To Excel" onclick="Button1_Click"/>
</div>
</form>
</body>
</html>
aspx.cs page:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using iTextSharp.text.html.simpleparser;
using System.IO;
using System.Data.SqlClient;
using System.Data;
public partial class Default2 : System.Web.UI.Page
{
protected
void Page_Load(object sender, EventArgs e)
{
}
protected
void Button1_Click(object sender, EventArgs e)
{
exportToExcel();
}
public void
exportToExcel()
{
Response.Clear();
Response.ContentType = "application/vnd.xls";
Response.AddHeader("content-disposition", "attachment;filename=ExportData1.xls");
StringWriter StringWriter = new System.IO.StringWriter();
HtmlTextWriter HtmlTextWriter = new HtmlTextWriter(StringWriter);
GridView1.RenderControl(HtmlTextWriter);
Response.Write(StringWriter.ToString());
Response.End();
}
}
No comments:
Post a Comment