Al Pascual



Geo RSS
Geo Twitter Timeline

Blogs I read

<January 2009>
SunMonTueWedThuFriSat
28293031123
45678910
11121314151617
18192021222324
25262728293031
1234567

Export DataGrid/GridView to Excel

Got to my attention the code on this old post is all screw up, please find the right version below.

/// <summary>
 /// Summary description for ExportToExcel.
 /// </summary>
 public class ExportToExcel
 {
  private Page m_pPage = null;
  public ExportToExcel(Page pPage)
  {
   m_pPage = pPage;
  }

  public void ExportDataGrid(System.Web.UI.WebControls.DataGrid dg)
  {
   System.Web.HttpContext context = System.Web.HttpContext.Current;
   //export to excel

   context.Response.Clear();
   context.Response.Buffer= true;
   context.Response.ContentType = "application/vnd.ms-excel";
   context.Response.Charset = "";
   m_pPage.EnableViewState = false;

   System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
   System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);

   this.ClearControls(dg);
   dg.RenderControl(oHtmlTextWriter);

   context.Response.Write(oStringWriter.ToString());

   context.Response.End();
  }

  private void ClearControls(Control control)
  {
   for (int i=control.Controls.Count -1; i>=0; i--)
   {
    ClearControls(control.Controls[i]);
   }

   if (!(control is TableCell))
   {
    if (control.GetType().GetProperty("SelectedItem") != null)
    {
     LiteralControl literal = new LiteralControl();
     control.Parent.Controls.Add(literal);
     try
     {
      literal.Text = (string)control.GetType().GetProperty("SelectedItem").GetValue(control,null);
     }
     catch

     {

     }

     control.Parent.Controls.Remove(control);
    }

    else

     if (control.GetType().GetProperty("Text") != null)
    {
     LiteralControl literal = new LiteralControl();
     control.Parent.Controls.Add(literal);
     literal.Text = (string)control.GetType().GetProperty("Text").GetValue(control,null);
     control.Parent.Controls.Remove(control);
    }
   }
   return;
  }

 }

You can also download it from here

Enjoy

Al

Comments

DotNetKicks.com said:

You've been kicked (a good thing) - Trackback from DotNetKicks.com

# November 28, 2007 11:37 AM

Ettore said:

Hi I just developed a nice tool to export data from Gridview to real XML or XLSX format for Excel 2003 and Excep 2007. Look at http://www.gridviewtoexcel.com
# December 8, 2007 4:39 AM

Mohammad Abu-Ali said:

Thank you for this example, I wonder if there's any other way to export to excel file without using the Response.Write() method ?? Many Thanks
# January 9, 2008 11:10 AM

naresh said:

image not export with this code, how to export image in excel

# August 4, 2008 3:57 AM