Solved

Commas in A Streamed CSV

Posted on 2006-06-26
7
525 Views
Last Modified: 2008-02-01
I am streaming a CSV file to the browser.

The problems that I'm presented with are the newline char, and the comma char - both for fairly obvious reasons.

I simply stripped the new line, but I don't want to remove the comma completly. One solution I attempted is to place quotes (both single and double) around the strings within the csv. The quotes are simply interpreted as part of the file, and not something denoting the start and end of a string, so this did not work (I am using a stringbuilder to concat my whole csv together before streaming if that is relevant). The other solution was to replace the comma character with an escaped comma ('\,'), but it's not recognized by VS as a valid escape sequence, and therefore craps out on compile.

Any ideas on how to handle this?

Thanks,
G
0
Comment
Question by:GENTP
  • 3
  • 2
7 Comments
 
LVL 96

Expert Comment

by:Bob Learned
ID: 16987823
.NET version?  2002, 2003, or 2005?

Bob
0
 
LVL 5

Author Comment

by:GENTP
ID: 16989041
2002. Framework V 1.1.

Thanks,
G
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 16996728
Where is the data coming from?  A DataTable?

Bob
0
 
LVL 5

Author Comment

by:GENTP
ID: 17076285
It's coming from looping through a SqlDataReader. I could switch the method I use if needed.

G
0
 
LVL 96

Accepted Solution

by:
Bob Learned earned 500 total points
ID: 17124757
This is what I use to stream CSV:

Public Class Export

  Private response As HttpResponse

  ' Exports data to a custom format
  Public Sub ExportCSV(ByVal data As DataTable, ByVal fileName As String)

    response = HttpContext.Current.Response

    response.Clear()
    response.ClearHeaders()
    response.Cache.SetExpires(DateTime.Now.AddSeconds(60))
    response.Expires = 1
    response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate)
    response.Cache.SetValidUntilExpires(False)
    response.CacheControl = "private"
    response.AddHeader("pragma", "cache")

    ' Add the header that specifies the default filename
    ' for the Download/SaveAs dialog
    response.AddHeader("Content-Disposition", "attachment;filename=" & fileName)

    Dim delimiter As String = String.Empty

    response.ContentType = "text/csv"

    Dim exportContent As String = ConvertDataTableToString(data, delimiter)

    If exportContent.Length <= 0 Then
      exportContent = "Error converting data"
    End If

    response.AddHeader("Content-Length", Encoding.UTF8.GetByteCount(exportContent))
    response.BinaryWrite(Encoding.UTF8.GetBytes(exportContent))

    ' Stop execution of the current page.
    response.End()

  End Sub  'ExportCSV

  Public Function ConvertDataTableToString(ByVal sourceData As DataTable, Optional ByVal Delimiter As String = Nothing, Optional ByVal Separator As String = ",") As String

    Dim resultBuilder As StringBuilder
    resultBuilder = New StringBuilder
    resultBuilder.Length = 0

    resultBuilder.Append(ControlChars.Quote)

    ' Add column headers.
    For Each sourceColumn As DataColumn In sourceData.Columns

      If Not Delimiter Is Nothing AndAlso (Delimiter.Trim.Length > 0) Then
        resultBuilder.Append(Delimiter)
      End If

      resultBuilder.Append(sourceColumn.ColumnName)

      If Not Delimiter Is Nothing AndAlso (Delimiter.Trim.Length > 0) Then
        resultBuilder.Append(Delimiter)
      End If

      resultBuilder.Append(Separator)

    Next sourceColumn

    If resultBuilder.Length > Separator.Trim.Length Then
      resultBuilder.Length = resultBuilder.Length - Separator.Trim.Length
    End If

    resultBuilder.Append(ControlChars.Quote)
    resultBuilder.Append(ControlChars.CrLf)

    ' Add data rows.
    For Each rowCurrent As DataRow In sourceData.Rows

      resultBuilder.Append(ControlChars.Quote)

      For Each columnCurrent As DataColumn In sourceData.Columns

        If Not Delimiter Is Nothing AndAlso (Delimiter.Trim.Length > 0) Then
          resultBuilder.Append(Delimiter)
        End If

        resultBuilder.Append(rowCurrent(columnCurrent.ColumnName))

        If Not Delimiter Is Nothing AndAlso (Delimiter.Trim.Length > 0) Then
          resultBuilder.Append(Delimiter)
        End If
        resultBuilder.Append(Separator)

      Next columnCurrent

      resultBuilder.Length = resultBuilder.Length - 1
      resultBuilder.Append(ControlChars.Quote)
      resultBuilder.Append(ControlChars.CrLf)

    Next rowCurrent

    Return resultBuilder.ToString()

  End Function

End Class

Bob
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Sometimes in DotNetNuke module development you want to swap controls within the same module definition.  In doing this DNN (somewhat annoyingly) swaps the Skin and Container definitions to the default admin selections.  To get around this you need t…
Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now