I have to export the data present in the datagridview to Microsoft Excel. It is a window application using c#. Does anyone know how to do it. Please help.
Thanks
I have to export the data present in the datagridview to Microsoft Excel. It is a window application using c#. Does anyone know how to do it. Please help.
Thanks
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.
shanmuganathan rajuPosted Dec 6, 2007, 5:02 AM
This Datagrid to Excel:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
public partial class ExcelSheet_ExportExcel : System.Web.UI.Page
{
GridView grdStudentMarks = new GridView();
Button btnExportToGrid = new Button();
protected void Page_Load(object sender, EventArgs e)
{
// SqlDataSource sds = new SqlDataSource(@"Data Source=Master\SQLEXPRESS; Initial Catalog=shan; User Id=shan; Password=Raju", "select * from MarkSheet");
grdStudentMarks.DataSource = sds;
grdStudentMarks.DataBind();
// Form.Controls.Add(grdStudentMarks);
Form.Controls.Add(btnExportToGrid);
string path = Context.Server.MapPath("Download.aspx");
btnExportToGrid.Text = "Export To Grid ";
btnExportToGrid.Click += new EventHandler(this.btnExportToGrid_Click);
}
void btnExportToGrid_Click(object sender, EventArgs e)
{
ExportGridToExcel(grdStudentMarks, "DynamicsDunction");
}
private void ExportGridToExcel(GridView grdGridView, string fileName)
{
IList list = new ArrayList();
Response.Clear();
Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.xls", fileName));
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
StringWriter stringWrite = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
grdGridView.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.Flush();
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
}
}