我最好如何生成下载使用ASP.NET CSV(逗号分隔的文本文件)? [英] How do I best generate a CSV (comma-delimited text file) for download with ASP.NET?

查看:241
本文介绍了我最好如何生成下载使用ASP.NET CSV(逗号分隔的文本文件)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我得到了什么。有用。但是,有一个简单的或更好的办法?

在一个ASPX页面,我已经得到了下载链接...

 < ASP:超链接ID =HyperLinkDownload=服务器NavigateUrl =〜/ Download.aspx>下载为CSV文件< / ASP:超链接>

然后,我已经得到了Download.aspx.vb code背后...

 公共部分类下载
    继承System.Web.UI.Page    保护小组的Page_Load(BYVAL发件人为对象,BYVAL E上System.EventArgs)把手Me.Load
        设置页眉
        Response.Clear()
        Response.ContentType =TEXT / CSV
        昏暗的文件名作为字符串=books.csv
        Response.AppendHeader(内容处置,附件;文件名=+文件名)        生成文件内容
        昏暗的分贝作为新bookDevelopmentDataContext
        昏暗Allbooks =从b在db.books _
                       ORDER BY b.Added _
                       的选择b
        昏暗CsvFile作为新的StringBuilder
        CsvFile.AppendLine(CsvHeader())
        对于每个B作为书Allbooks
            CsvFile.AppendLine(bookString(b)条)
        下一个        '写入文件
        的Response.Write(CsvFile.ToString)
        到Response.End()
    结束小组    功能CsvHeader()作为字符串
        昏暗CsvLine作为新的StringBuilder
        CsvLine.Append(已发布)
        CsvLine.Append(标题)
        CsvLine.Append(作者)
        CsvLine.Append(价格)
        返回CsvLine.ToString
    结束功能    功能bookString(BYVAL b以书)作为字符串
        昏暗CsvLine作为新的StringBuilder
        CsvLine.Append(b.Published.ToShortDateString +,)
        CsvLine.Append(b.Title.Replace(,,)+,)
        CsvLine.Append(b.Author.Replace(,,)+,)
        CsvLine.Append(格式(b.Price,C)。替换(,))
        返回CsvLine.ToString
    结束功能末级


解决方案

CSV格式有一些陷阱。你有没有问过自己这些问题:


  • 请问我的任何数据都嵌入的逗号?

  • 请问我的任何数据都嵌入双引号?

  • 请问我的任何数据都必须换行?

  • 请我需要支持的Uni code字符串?

我看到上面的code几个问题。逗号的事情首先...你剥逗号:

  CsvLine.Append(格式(b.Price,C)。替换(,))

为什么呢?在CSV,你应该围绕什么有逗号与报价:

  CsvLine.Append(的String.Format(\\{0:C} \\,b.Price))

(或类似的东西...我的VB是不是很好)。如果你不能确定是否有逗号,但是把引号的。如果在字符串中的引号,你需要加倍他们逃离他们。 变成

  b.Title.Replace(\\,\\\\)

然后用双引号,如果你想环绕这个。如果在您的字符串换行,你需要包围字符串引号......是的,新行的允许的CSV文件。它看起来怪异的人类,但是这一切都很好。

有一个良好的CSV作家需要一些思考。一个良好的CSV阅读器(分析器)是简直硬(没有,没有正则表达式解析CSV ......只会让你的存在方式约95%不够好)。

再有就是统一code ...或更一般I18N(国际化)的问题。例如,你是逗号剥离出一个格式化的价格。但是,这是假设你指望它在美国的价格被格式化。在法国,数字格式为扭转(用来代替逗号句号和反之亦然的)。底线,利用文化无关的格式尽可能。

虽然这里的问题是的生成的CSV,难免你需要解析CSV。在.NET中,我发现(免费)最好的解析器快速的CSV阅读器 $ C $的CProject 。其实我已经用它在生产code,这是真的快,非常好用!

This is what I've got. It works. But, is there a simpler or better way?

One an ASPX page, I've got the download link...

<asp:HyperLink ID="HyperLinkDownload" runat="server" NavigateUrl="~/Download.aspx">Download as CSV file</asp:HyperLink>

And then I've got the Download.aspx.vb Code Behind...

Public Partial Class Download
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'set header
        Response.Clear()
        Response.ContentType = "text/csv"
        Dim FileName As String = "books.csv"
        Response.AppendHeader("Content-Disposition", "attachment;filename=" + FileName)

        'generate file content
        Dim db As New bookDevelopmentDataContext
        Dim Allbooks = From b In db.books _
                       Order By b.Added _
                       Select b
        Dim CsvFile As New StringBuilder
        CsvFile.AppendLine(CsvHeader())
        For Each b As Book In Allbooks
            CsvFile.AppendLine(bookString(b))
        Next

        'write the file
        Response.Write(CsvFile.ToString)
        Response.End()
    End Sub

    Function CsvHeader() As String
        Dim CsvLine As New StringBuilder
        CsvLine.Append("Published,")
        CsvLine.Append("Title,")
        CsvLine.Append("Author,")
        CsvLine.Append("Price")
        Return CsvLine.ToString
    End Function

    Function bookString(ByVal b As Book) As String
        Dim CsvLine As New StringBuilder
        CsvLine.Append(b.Published.ToShortDateString + ",")
        CsvLine.Append(b.Title.Replace(",", "") + ",")
        CsvLine.Append(b.Author.Replace(",", "") + ",")
        CsvLine.Append(Format(b.Price, "c").Replace(",", ""))
        Return CsvLine.ToString
    End Function

End Class

解决方案

CSV formatting has some gotchas. Have you asked yourself these questions:

  • Does any of my data have embedded commas?
  • Does any of my data have embedded double-quotes?
  • Does any of my data have have newlines?
  • Do I need to support Unicode strings?

I see several problems in your code above. The comma thing first of all... you are stripping commas:

CsvLine.Append(Format(b.Price, "c").Replace(",", ""))

Why? In CSV, you should be surrounding anything which has commas with quotes:

CsvLine.Append(String.Format("\"{0:c}\"", b.Price))

(or something like that... my VB is not very good). If you're not sure if there are commas, but put quotes around it. If there are quotes in the string, you need to escape them by doubling them. " becomes "".

b.Title.Replace("\"", "\"\"")

Then surround this by quotes if you want. If there are newlines in your string, you need to surround the string with quotes... yes, literal newlines are allowed in CSV files. It looks weird to humans, but it's all good.

A good CSV writer requires some thought. A good CSV reader (parser) is just plain hard (and no, regex not good enough for parsing CSV... it will only get you about 95% of the way there).

And then there is Unicode... or more generally I18N (Internationalization) issues. For example, you are stripping commas out of a formatted price. But that's assuming the price is formatted as you expect it in the US. In France, the number formatting is reversed (periods used instead of commas, and vice versa). Bottom line, use culture-agnostic formatting wherever possible.

While the issue here is generating CSV, inevitably you will need to parse CSV. In .NET, the best parser I have found (for free) is Fast CSV Reader on CodeProject. I've actually used it in production code and it is really really fast, and very easy to use!

这篇关于我最好如何生成下载使用ASP.NET CSV(逗号分隔的文本文件)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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