如何服务于ASP.NET Web窗体视图为CSV [英] How to serve a View as CSV in ASP.NET Web Forms

查看:161
本文介绍了如何服务于ASP.NET Web窗体视图为CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个MS SQL查看我希望可为CSV下载我的ASPNET Web窗体应用程序。我使用实体框架为项目中的其他视图和表。什么是启用此下载的最佳方式?

I have a MS SQL view that I want to make available as a CSV download in my ASPNET Web Forms app. I am using Entity Framework for other views and tables in the project. What's the best way to enable this download?

我可以添加一个LinkBut​​ton的click处理迭代来看,其写入CSV格式的磁盘,然后提供该文件。不过,我倒是preFER不写入磁盘,如果能够避免它,这涉及到迭代code,可能与一些其他的解决办法是可以避免的。

I could add a LinkButton whose click handler iterates over the view, writes its CSV form to the disk, and then serves that file. However, I'd prefer not to write to the disk if it can be avoided, and that involves iteration code that may be avoided with some other solution.

推荐答案

您可以遍历数据集,但不是创建服务器上的CSV文件只需通过HTTP响应返回。下面的函数应该做的伎俩。

You could iterate over the dataset, but instead of creating the CSV file on your server simply return it through the HTTP response. The following function should do the trick.

Public Shared Sub ExportTextFile(ByVal response As System.Web.HttpResponse, ByVal text As String, ByVal fileName As String)

    response.Clear()
    response.AddHeader("content-disposition", String.Format("attachment;filename={0}", fileName))
    response.Charset = ""
    response.Cache.SetCacheability(HttpCacheability.NoCache)
    response.ContentType = "application/vnd.text"

    Dim stringWrite As New System.IO.StringWriter
    Dim htmlWrite = New HtmlTextWriter(stringWrite)
    response.Write(text.ToString)
    response.End()

End Sub

这篇关于如何服务于ASP.NET Web窗体视图为CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆