Html Export to Excel

Html Export to Excel

for exporting to excel just call the function below in sample code and pass the page object from an aspx and the aspx page contents are rendered in excel..

make control.visible = false in the page if you dont want those controls to be exported to excel.

the same function can be overloaded to pass say a datagrid (in most search screens we need results only)also.

 

// For Direct Exporting From  HTML to excel
  // Call this function on Button Click
  public static void HtmlExportToExcel(Page PageObject)

  {
 
   HttpContext.Current.Response.Buffer = true;
   HttpContext.Current.Response.Clear();

   HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";

   HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;
   HttpContext.Current.Response.AddHeader("content-disposition",
    "attachment; filename=Export-" + System.DateTime.Now.ToString("MMMddyyyy-hhmmtt") +   ".xls");
   HttpContext.Current.Response.Charset = string.Empty ;

   PageObject.EnableViewState = false;

   StringWriter tw = new StringWriter();

   HtmlTextWriter hw = new HtmlTextWriter(tw);

   PageObject.RenderControl (hw);
      HttpContext.Current.Response.Write(tw.ToString());

   HttpContext.Current.Response.Flush() ;

   HttpContext.Current.Response.Close();
  }

Comments

  • Anonymous
    June 24, 2011
    it's running ... but file format save data in Html Table Format like <TD>               <TR> "Name" </TR>              <TR> "Address" </TR>       </TD> i Want To Save in .Xls File Format

  • Anonymous
    June 24, 2011
    hi did u try use to save as option in excel and save it as a excel workbook..