How to import the gridview data in to excel. i want to see the record in excel format how to do?
How to import the grid view data in to excel. i want to see the record in excel format how to do?
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Satyapriya NayakPosted Dec 26, 2011, 11:51 AM
Try this...
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="import_the_gridview_data_in_excel._Default" %>
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;
using System.Text;
namespace import_the_gridview_data_in_excel
{
public partial class _Default : System.Web.UI.Page
{
string connStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(connStr);
SqlDataAdapter sqlda = new SqlDataAdapter("SELECT * from employee", conn);
DataSet ds = new DataSet();
sqlda.Fill(ds, "employee");
GridView1.DataSource = ds;
GridView1.DataMember = "employee";
GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
ExportToExcel("Report.xls", GridView1);
}
private void ExportToExcel(string strFileName, GridView dg)
{
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "";
this.EnableViewState = false;
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
GridView1.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
}
}
}
Thanks
If this post helps you mark it as answer