Export gridview to word in asp.net c#

Here we will discuss how we can download gridview data to word document in asp.net using c#.net. Here I have developed an asp.net website where we have used a gridview to bind the data from SQL server table and then we have a button, on the button click we are exporting the data to word format.

Below is the .aspx code.

<asp:GridView ID=”GridView1″ runat=”server”></asp:GridView><br />
<asp:Button ID=”btnDownload” runat=”server” Text=”Download” OnClick=”btnDownload_Click” />

.aspx.cs code:

Below is the .cs code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.IO;
using System.Configuration;



namespace EnjoySharePointBackup
{
public partial class _Default : Page
{

private SqlConnection con;
private SqlCommand com;
private string constr, query;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Bindgrid();

}
}
public override void VerifyRenderingInServerForm(Control control)
{
//base.VerifyRenderingInServerForm(control);
}
private void connection()
{
string constr = “Data Source=YourDataSource;database=EnjoySharePoint;User ID=User1;Password=**********;”;
con = new SqlConnection(constr);
con.Open();

}
protected void btnDownload_Click(object sender, EventArgs e)
{
ExportGridToword();
}
private void Bindgrid()
{
connection();
query = “select * from jobmaster where JobID”+ TextBox1.Text;
com = new SqlCommand(query, con);
SqlDataReader dr = com.ExecuteReader();

GridView1.DataSource = dr;
GridView1.DataBind();
con.Close();

}

private void ExportGridToword()
{
Response.Clear();
Response.Buffer = true;
Response.ClearContent();
Response.ClearHeaders();
Response.Charset = “”;
string FileName = “EnjoySharePoint” + DateTime.Now + “.doc”;
StringWriter strwritter = new StringWriter();
HtmlTextWriter htmltextwrtter = new HtmlTextWriter(strwritter);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = “application/msword”;
Response.AddHeader(“Content-Disposition”, “attachment;filename=” + FileName);
GridView1.GridLines = GridLines.Both;
GridView1.HeaderStyle.Font.Bold = true;
GridView1.RenderControl(htmltextwrtter);
Response.Write(strwritter.ToString());
Response.End();


}
}
}

Hope this help you to export gridview data to word in asp.net using c#.net.


You May Also like the Following SharePoint Online Tutorials:

About Bijay Kumar

I am Bijay from Odisha, India. Currently working in my own venture TSInfo Technologies in Bangalore, India. I am Microsoft Office Servers and Services (SharePoint) MVP (5 times). I works in SharePoint 2016/2013/2010, SharePoint Online Office 365 etc. Check out My MVP Profile.. I also run popular SharePoint web site SharePointSky.com

View all posts by Bijay Kumar →

Leave a Reply