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

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>