Export gridview records to word file

Satyapriyanayak
Posted by Satyapriyanayak under ASP.NET category on | Points: 40 | Views : 1217
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Export_to_word._Default" %>

<!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>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView id="g1" Runat="Server" AutoGenerateColumns="true">

</asp:GridView>
</div>
<asp:Button ID="btn_export" runat="server" onclick="btn_export_Click"
Text="Export to word" />
</form>
</body>
</html>




using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
namespace Export_to_word
{
public partial class _Default : System.Web.UI.Page
{
string connStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlCommand com;
SqlDataAdapter sqlda;
DataSet ds;
string str;

protected void Page_Load(object sender, EventArgs e)
{
bindgrid();
}
void bindgrid()
{
SqlConnection con = new SqlConnection(connStr);
con.Open();
str = "select * from employee";
com = new SqlCommand(str, con);
sqlda = new SqlDataAdapter(com);
ds = new DataSet();
sqlda.Fill(ds, "employee");
g1.DataMember = "employee";
g1.DataSource = ds;
g1.DataBind();
con.Close();
}

protected void btn_export_Click(object sender, EventArgs e)
{

Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=Gridviewdata.doc");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.word";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
g1.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}

public override void VerifyRenderingInServerForm(Control control)
{
}
}
}

Comments or Responses

Login to post response