How do I best generate a CSV (comma-delimited text file) for download with ASP.NET?

后端 未结 8 1191
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-14 18:46

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...



        
8条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-14 19:17

    Looking mostly good except in your function "BookString()" you should pass all those strings through a small function like this first:

    Private Function formatForCSV(stringToProcess As String) As String
        If stringToProcess.Contains("""") Or stringToProcess.Contains(",") Then
            stringToProcess = String.Format("""{0}""", stringToProcess.Replace("""", """"""))
        End If
        Return stringToProcess
    End Function
    
    'So, lines like this:
    CsvLine.Append(b.Title.Replace(",", "") + ",")
    'would be lines like this instead:
    CsvLine.Append(formatForCSV(b.Title)) + ",")
    

    The function will format your strings well for CSV. It replaces quotes with double quotes and add quotes around the string if there are either quotes or commas in the string.

    Note that it doesn't account for newlines, but can only safely guarantee good CSV output for those strings that you know are free of newlines (inputs from simple one-line text forms, etc.).

提交回复
热议问题