Saturday, September 5, 2009

Exporting DataSet to Excel


Exporting Dataset to Excel is not a big deal. Wide range of help related to it is available on the net. This article for Exporting Dataset to Excel with the idea that the beneficiary will only need to COPY, PASTE and USE it.

Here is the code.

Add a class and copy the below code into it:

using System;
using System.Data;
using System.Configuration;
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;

public class ExportDataset
{
public void ExportToExcel(DataSet dSet, int TableIndex, HttpResponse Response, string FileName)
{
Response.Clear();
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("content-disposition", "attachment; filename=" + FileName + ".xls");
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw);
GridView gv = new GridView();
gv.DataSource = dSet.Tables[TableIndex];
gv.DataBind();
gv.RenderControl(hw);
Response.Write(sw.ToString());
Response.End();
}
}


And copy the following code on the Button Click Event (or at appropriate place):

SqlConnection con = new SqlConnection("Server=TestServer;uid=test;pwd=test;database=test;");
con.Open();
SqlDataAdapter adp = new SqlDataAdapter("select * from BTA_tblTimeEntry", con);
DataSet ds = new DataSet();
adp.Fill(ds);
ExportDataset objExport = new ExportDataset();
objExport.ExportToExcel(ds, 0, Response, "Report");
con.Close();


0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.