Export HTML Table to Excel using ASP.NET

hotcoder picture hotcoder · Feb 20, 2012 · Viewed 82.3k times · Source

I have an html table (Not Gridview) and that has no proper Header and rows. Instead it has customized structure and data. I want to export this table to Excel. How can I do using ASP.NET? enter image description here

The labels are fixed text and the integer values are coming from database. So the table structure is fixed only the integer/decimal values change.

Answer

Arun Singh picture Arun Singh · Mar 21, 2012

You want Export HTML table (Not Gridview) customized structure and data to Excel using ASP.NET.

Try the following Approach

  1. Provide the ID and add runat="server" attribute

    <table id="tbl" runat="server" >

  2. Add the following code

    Response.ContentType = "application/x-msexcel"; 
    Response.AddHeader("Content-Disposition", "attachment;
    filename=ExcelFile.xls");
    Response.ContentEncoding = Encoding.UTF8; 
    StringWriter tw = new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(tw);
    tbl.RenderControl(hw);
    Response.Write(tw.ToString());
    Response.End();