Exporting from an HTML table to a Spreadsheet



Hi there,

I have a asp.net page that dynamically constructs a table based on data
retrieved from a database. This is an excerpt of the code used:

' Create a row
Dim row As HtmlTableRow = New HtmlTableRow
' Create a column and add it to the row
Dim cell As HtmlTableCell = New HtmlTableCell
cell.InnerText = sValue
' ... other columns created and added...
tblSummaryTable.Rows.Add(row) ' tblSummaryTable already exists on page,
running at server
' ... loop to add more rows as needed...

Now I need to export this table to a spreadsheet when the user clicks a
button on the page.

I have tried a variety of routines, suggestions, etc. None of them have
worked. I only get an empty spreadsheet, sometimes with very wide column (I
don't know why).

Almost all examples I have seen involve the use of datasets/datagrids. For
reasons not relevant to the question, I cannot use datagrids for this.

The question is: Can an HTML table be exported or converted to a spreadsheet
directly (or through a routine, whatever)?

Many thanks,

Peter Bromberg [C# MVP]

This sample is for a GridView, but it should work for any servercontrol:

// you also need this to suppress "not inside Form tag" errors on
public override void VerifyRenderingInServerForm(Control control)
// no-op, just override so base doesn't do anything
protected void lnkExport_Click(object sender, EventArgs e)

Response.Charset = "";
// If you want the option to open the Excel file without saving
// uncomment the line below
Response.ContentType = "application/vnd.xls";
StringWriter stringWrite = new StringWriter();
HtmlTextWriter htmlWrite =
new HtmlTextWriter(stringWrite);



Thanks, Peter, for your response. Unfortunately, that routine I have tried
it in several different forms with no desirable results. You say it should
work with any server control, but for some reason, it does not do it for me.
Probably I am missing something. But anyway, I really appreciate your reply.


Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question