开发者

Trouble creating csv for download

开发者 https://www.devze.com 2023-01-12 14:39 出处:网络
Using this lovely example I am getting some funky results.What I have is: Protected Sub btnCSV_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCSV.Click

Using this lovely example I am getting some funky results. What I have is:

Protected Sub btnCSV_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCSV.Click

    Response.Clear()
    Response.Buffer = True
    Response.ContentType = "text/csv"
    Response.AppendHeader("Content-Disposition", "inline; filename=" + FileName + ".csv")

    CsvHelper.ProduceCSV(dt, Response.Output, True)

End Su开发者_高级运维b

But what is happening is that the csv file contains the html output from the page as well as the csv data from the CsvHelper. What gives?


When btnCSV is clicked your event-handler method sends the CSV data to the response buffer. But once the method finishes executing, the remainder of the page lifecycle continues, sending the normal page markup to the response buffer. This is why you have HTML appended to the CSV.

To prevent this you'll need to end the request as soon as the CSV data has been generated. You'll probably want to call Application.CompleteRequest, or similar, following your ProduceCSV call.

Edit...

After taking a look at the documentation, rather than relying on my memory, it seems that the HttpApplication object isn't exposed within a standard ASP.NET page, in which case you'll probably need to use Response.End instead. Not ideal, but it'll do the trick.


After the click you want to show the normal page + offer the file you created, yes? There's a slight difference: use attachtment instead of inline.

Response.ContentType = "application/octet-stream"
Response.AddHeader("Content-Disposition", _
  "attachment; filename=""" & filename & """")
0

精彩评论

暂无评论...
验证码 换一张
取 消