Solved

Commas in A Streamed CSV

Posted on 2006-06-26
7
538 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

ScreenConnect 6.0 Free Trial

Discover new time-saving features in one game-changing release, ScreenConnect 6.0, based on partner feedback. New features include a redesigned UI, app configurations and chat acknowledgement to improve customer engagement!

Question has a verified solution.

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

ASP.Net to Oracle Connectivity Recently I had to develop an ASP.NET application connecting to an Oracle database.As I am doing it first time ,I had to solve several problems. This article will help to such developers  to develop an ASP.NET client…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Two types of users will appreciate AOMEI Backupper Pro: 1 - Those with PCIe drives (and haven't found cloning software that works on them). 2 - Those who want a fast clone of their boot drive (no re-boots needed) and it can clone your drive wh…
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

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