Monday, August 27, 2007

Datagrid to excel using ASP.NET

Datagrid to excel using ASP.NET
===========================


Two things to be done:
1) Fetch data from datasource and bind to datagrid
2) Pass the datagrid to ExportToExcel function. The content type should be application/vnd.ms-excel



//convert to excel from httpresponse
private void ExportToExcel(DataGrid dgExport, HttpResponse response )
{
response.Clear();
response.Charset = "";
response.ContentType ="application/vnd.ms-excel";

System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.Html32TextWriter htmlWrite = new System.Web.UI.Html32TextWriter(stringWrite) ;

DataGrid dg=new DataGrid();
dg=dgExport;

dg.GridLines =GridLines.None;
dg.HeaderStyle.Font.Bold =true;
dg.HeaderStyle.ForeColor =System.Drawing.Color.Red;
dg.ItemStyle.ForeColor =System.Drawing.Color.Black;


dg.DataBind();
dg.RenderControl(htmlWrite);
response.Write(stringWrite.ToString());
response.End();

}

//fetch date from datasource and bind to grid

private void cmdMakeExcel_Click(object sender, System.EventArgs e)
{
try
{
string strSQL = txtQuery.Text.ToString();
SqlDataAdapter daa = new SqlDataAdapter(strSQL, Connection.getConn());


DataSet Dsss = new DataSet();

daa.Fill(Dsss);
daa.FillSchema(Dsss,SchemaType.Mapped);
DataGrid Dss=new DataGrid();

Dss.DataSource = Dsss;
Dss.DataBind();

ExportToExcel(Dss,Response);
}
catch
{
Response.Write("Could Not Process");
}
}

No comments: