?
Solved

Commas in A Streamed CSV

Posted on 2006-06-26
7
Medium Priority
?
566 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 2000 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

On Demand Webinar - Networking for the Cloud Era

This webinar discusses:
-Common barriers companies experience when moving to the cloud
-How SD-WAN changes the way we look at networks
-Best practices customers should employ moving forward with cloud migration
-What happens behind the scenes of SteelConnect’s one-click button

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
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…
Michael from AdRem Software outlines event notifications and Automatic Corrective Actions in network monitoring. Automatic Corrective Actions are scripts, which can automatically run upon discovery of a certain undesirable condition in your network.…
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…
Suggested Courses

770 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