繁体   English   中英

允许用户下载动态csv文件asp.net

[英]allow user to download dynamic csv file asp.net

我希望允许我的用户点击“下载”按钮,然后动态构建动态csv文件,并提示用户下载。 我知道如何使用HTTPHandler构建文件,但不太确定通过下载传递内容的机制。

我通常创建一个Generic Handler(.ashx)并执行以下操作:

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());
}

现在,如果您正在构建的CSV非常大,您可能希望在创建它时写出每一行,而不是将其填充到StringBuilder中。

只需在HTTP Handler代码中发出Content-Disposition HTTP标头。 大多数浏览器会将其解释为下载请求。 用您希望用户看到的文件名替换yourfile.csv

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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