SoFunction
Updated on 2025-03-06

C# Method to export GridView control to EXCEL using RenderControl

This article shows the example of C# using RenderControl to export GridView control to EXCEL. It is a very practical function and is shared with you for your reference. The details are as follows:

The main function codes are as follows:

// Output GridView to Excel fileprivate void ExportExcel(GridView gridView, string title, string title2, string fileName)
{
  int nHideCols = 0;
  //If you don't want to output a certain column, set Visible to false  for (int i = 0; i < ; i++)
  {
 if ([i].HeaderText == "Device Status")
 {
   [i].Visible = false;
   [i]. = 0;
   nHideCols = 1;
   break;
 }
  }
  //Set the display character set   = "utf-8";
  //Set the content character set   = ("utf-8"); 

  //Set the file name  ("Content-Disposition", "attachment;filename=" + (fileName, Encoding.UTF8).Replace('+', '_').Replace('-', '_'));
  //Set the file type. It can also be application/ms-word or text/html (character set is set to gb2312)   = "application/ms-excel";
   = false;
  using (StringWriter tw = new StringWriter())
  {
 using (HtmlTextWriter hell = new HtmlTextWriter(tw))
 {
    = false;
   (hell);
   string s = ();
   s = ("\r\n", "");
   int index = ("<tr");
   //Can customize the title of Excel file   string head = "<tr><td colspan=\"" + ( - nHideCols).ToString() + "\" style=\"text-align: center; height: 42px; font-size: 24px; font-weight: bolder; color: #000000;\">" + title + "</td></tr>" +
   "<tr><td colspan=\"" + ( - nHideCols).ToString() + "\" style=\"text-align: center; height: 24px; font-size: 12px; color: #000000;\">" + title2 + "</td></tr>";
   //Use Index to determine whether there is data, of course it can also be used to judge   if (index != -1)
   {
 //With data s = (index, head);
   }
   else
   {
 //When there is no data s = "<table cellspacing=\"0\" cellpadding=\"3\" rules=\"rows\" border=\"1\" id=\"" +  + "\" style=\"background-color:White;border-color:#E7E7FF;border-width:1px;border-style:None;border-collapse:collapse;\">" +
   head + "</table>";
   }
   (s);
   ();
 }
  }
}
// At the same time, vs2005 and vs2003 will report an error "type "ExGridView" control "GridViewMaster" must be placed in the form mark with runat=server//The following method needs to be added to cancel verification of GridViewMaster controlpublic override void VerifyRenderingInServerForm(Control control)
{
  if (!().Equals(()))
  {
 (control);
  }
}

The example code in this article has detailed comments, which should not be difficult to understand. I hope this example will be helpful to everyone's C# programming.