Asp – Excel Export In ASP.NET + VB.NET Bug

asp.netvb.net

We use a small bit of excel exporting code in our app code at work to export XML controls from our ASP pages into an excel format using the following code:

  Public Shared Sub Export(ByRef xml As Xml, ByVal filename As String)
    Dim response As HttpResponse = HttpContext.Current.Response()
    response.Clear()
    response.AddHeader("content-disposition", "attachment;filename=" & filename & ".xls")
    response.ContentType = "application/vnd.ms-excel"
    Dim s As System.IO.StringWriter = New System.IO.StringWriter
    Dim htw As HtmlTextWriter = New HtmlTextWriter(s)
    xml.RenderControl(htw)
    response.Write(s.ToString)
    response.End()
  End Sub

This is all fine, except we've encountered a rather frustrating bug. If the XML control has a link in it then the export code is called again. We have a button which will say "Export to Excel" from the .aspx page which simply calls ExcelExport.Export(Xml1, "MyFileName") which is in a LinkButton click event.

Here's the order of events based on the form submit (selecting filters)

  • Enter filters
  • Submit form
  • Page_Load occurs
  • Submit button click event occurs

Clicking the export button

  • Page_Load
  • Export link button click event

Happy days so far, but then straight after the previous event, this is what happens when you click on a hyperlink within the XML control (the rendered XSLT page)

  • Page_Load
  • Export link button click event

So the user submits a form which loads up the XML control in a nice viewable XSLT page. Then they click "export to excel" which will give them the page in excel instead, then they click on the XSLT page, for example a link, but the save dialog for excel comes up again. We've gone through the series of events, and if we do not call the excel exporter it goes through the series of events as normal. If we do call the excel exporter it will go through the page load event and unexpectedly go into the link button click event.

We've tried everything we can think of to try and fix this bug without any luck. Any ideas as to why this is happening?

Best Answer

You can export your data as .csv file format. You can export your data like this:

response.Clear()

response.AddHeader("content-disposition", "attachment;filename=" & filename & ".csv")

response.write "1,""John"",""Smith"",1976"+vbcrlf
response.write "2,""Joe"",""Black"",1963"+vbcrlf
response.write "1,""Morgan"",""Smith"",2003"+vbcrlf

response.End()
Related Topic