Wednesday, April 04, 2007

Export more than 1 Grid in Excel File

Hi Folks,

This Post is to tell you how to export more than 1 grid in 1 excel file.
this is a tricky post since we all know that its easy to export any complex data controls in asp.net 1.x or asp.net 2.0 to excel,but we will show how to export more than 1 complex data control into 1 excel file.

Here's the code in C# :

DataGrid1.DataSource=ds.Tables[0];
DataGrid1.DataBind();

DataGrid2.DataSource=ds.Tables[1];
DataGrid2.DataBind();

//export to excel
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);

System.Web.UI.HtmlTextWriter oHtmlTextWriter2 = new System.Web.UI.HtmlTextWriter(oStringWriter);

oHtmlTextWriter.RenderBeginTag(HtmlTextWriterTag.Br);
DataGrid1.RenderControl(oHtmlTextWriter);
oHtmlTextWriter.RenderEndTag();

oHtmlTextWriter2.RenderBeginTag(HtmlTextWriterTag.Br);
DataGrid2.RenderControl(oHtmlTextWriter2);

Response.Write(oStringWriter.ToString());
Response.Flush();
Response.End();

/***************************************************************/

in the previous code i have 2 datagrids and i export both of them in excel file using htmlTextWriter object ,and one string writer for both of them.


Regards,
Moustafa arafa

2 comments:

marriedman said...

Dear Mostafa,

Great approach as always.

regard
Ahsan

Vikt said...

hi it's a great example, but what can I do to export more than a server control in different excel sheets.

Control1 in sheet1
Control2 in sheet2
...

thx