简体   繁体   中英

allow user to download dynamic csv file asp.net

I want to allow my user to click on a button that says "download" and then will build a dynamic csv file on the fly and will prompt the user to download. I know how to build the file using a HTTPHandler, but not quite sure the mechanism for delivering the content via download.

I usually create a Generic Handler (.ashx) and do something like this:

public void ProcessRequest(HttpContext context)
{
   StringBuilder myCsv = new StringBuilder();
   foreach(myRow r in myRows) {
     myCsv.AppendFormat("\"{0}\",{1}", r.MyCol1, r.MyCol2);
   }

   context.Response.ContentType = "application/csv";
   context.Response.AddHeader("content-disposition", "attachment; filename=myfile.csv");
   context.Response.Write(myCsv.ToString());
}

Now if the CSV you're building is REALLY big, you might want to write out each row as you create it, rather than stuffing it into a StringBuilder.

Just emit a Content-Disposition HTTP header in your HTTP Handler code. Most browsers will interpret that as a download request. Replace yourfile.csv by the filename you want the user to see.

context.Response.ContentType = "text/csv";
context.Response.AddHeader("Content-Disposition", "attachment; filename=yourfile.csv");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM