1

I am exporting a HTML table to excel by sending the data as a HTML Table string and setting the content headers:

Dim html as String = "<table><tr><td>example<td></tr></table>"

context.Response.Clear()
context.Response.AddHeader("Content-Disposition", "attachment; filename=" & "exceldata-" & Now.ToString("yyyyMMddHHmmss") & ".xls")
'context.Response.AddHeader("Content-Length", ????)
context.Response.ContentType = "application/octet-stream"
context.Response.Write(response)
context.Response.End()

Is there a simple way of setting the content-length based on the size of the html string? Or should I just leave it blank anyway...would be nice to have the content-length ideally...

I am returning this using a GenericHandler in asp.net

davidsleeps
  • 9,393
  • 11
  • 59
  • 73

3 Answers3

5

Replace with the encoding of your choice, probably UTF8. Sorry for the C#:

ASCIIEncoding encoding = new ASCIIEncoding();
byte[] bytes = encoding.GetBytes(html);
int length = bytes.Length;

Source: http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.contentlength.aspx

John Sheehan
  • 77,456
  • 30
  • 160
  • 194
1

This seems too easy, but is it not just equal to html.Length?

benr
  • 216
  • 2
  • 6
1

I haven't used ASP.NET, but I guess that the Length() method returns the length of the string in chars, not bytes, so it won't work if your server uses UTF-8 or Unicode for serving the pages.

As noted in another answer, just let the server fill it for you. If you think about it, you don't have to add it when you generate HTML pages from ASP since the web server would generate it based in the response from the ASP module.

Alberto Martinez
  • 2,620
  • 4
  • 25
  • 28