Monday, June 11, 2007

Export To Excel using ASP.NET

Export to excel using Asp.net
==================================

In some of the situation you want to generate a excel sheet dynamically from a dataset. This can be easily done as explained below. You need t
//excel init logic
public void generateExcel(){
//connection related stuff
string myConnectionString="Server=(local);uid=sa;pwd=myPassword;database=myDataBaseName";
string mySql="select * from myTable";
SqlConnection myCon= new SqlConnection(myConnectionString);
//data you want to show in your excel sheet
SqlDataAdapter myDataAdapter = new SqlDataAdapter(mySql, myCon);
myCon.Open();

DataSet myDataSet = new DataSet();

myDataAdapter.Fill(myDataSet);
myDataAdapter.FillSchema(myDataSet,SchemaType.Mapped);

//pass a grid object..
DataGrid myDataGrid=new DataGrid();
myDataGrid.DataSource = myDataSet;
myDataGrid.DataBind();
//generation of excel sheet logic
ExportToExcel(myDataGrid,Response);
}


//excel generation logic
private void ExportToExcel(DataGrid dgExport, HttpResponse response ) {
//setting excel content type
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;
//excel design settings
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();
}

No comments: