Matthew Sanford
Matthew Sanford

Reputation: 1099

How to download a CSV file from an ASP page after user clicks a button

I basically have put the following into my button click even handler, and it works mostly but it also writes out all the html of the page too in the CSV file. Is there a way to stop this?

                    StringBuilder sb = new StringBuilder();
                sb.AppendLine("pkey,epsn,Cal. Date (UTC),Va Mult, Vb Mult, Vc Mult,Ia Mult, Ib Mult, Ic Mult, Ia Phase, Ib Phase, Ic Phase, CT Rating, CT Type, Cal By");
                Response.ContentType = "application/csv";

                Response.AddHeader("content-disposition", "attachment; filename=EPSn.csv");
                Response.Write(sb.ToString());
                foreach (DataRow row in dt.Rows)
                {
                    sb = new StringBuilder((string)row[0]);
                    for (int i = 1; i < dt.Columns.Count; i++)
                    {
                        if (row[i] is DBNull)
                            sb.Append(",NULL");
                        else if (i == 2)
                            sb.Append("," + new DateTime((long)row[i]).ToString("G"));
                        else
                            sb.Append("," + row[i].ToString());

                    }
                    sb.AppendLine();
                    Response.Write(sb.ToString());

Upvotes: 0

Views: 3561

Answers (4)

Chris Diver
Chris Diver

Reputation: 19812

Before you start to write the response add.

Response.Clear();

Add the following at the end of your code.

Response.Flush();
Response.End();

Kudos the the following question about the best way to end the response.

HttpResponse.End vs HttpResponse.Close vs HttpResponse.SuppressContent

Upvotes: 2

bdoshi
bdoshi

Reputation: 1071

I think you should also have Response.End() after this code: So that no more response is added to the response stream. That may be adding page output to your CSV.

sb.AppendLine();
Response.Write(sb.ToString());

Response.End();

Upvotes: 1

Aaron Anodide
Aaron Anodide

Reputation: 17186

I don't know if you're trying to avoid excel, but this snippet works in my code:

    void InitAttachment()
    {
        string attachment = "attachment; filename= " + this.FileName;
        Response.ClearContent();
        Response.AddHeader("content-disposition", attachment);
        Response.ContentType = "application/excel";
    }

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038800

Is there a way to stop this?

You could clear the response:

Response.Clear();
Response.ClearContent();

Also please stop rolling your own CSV parser. It's absolutely horrible, I see people continue doing this mistake over and over again.

Upvotes: 0

Related Questions