Visual Basic.Net - CSV file formatting

My program needs to create a CSV file.

I'm having issues writing this string to a text file that will meet CSV standards.  In particular, my program is not creating a file that can be opened with MS Excel and have all the data in the correct column.  My format is thrown out of skew when I encounter stirngs that have the delimiter (comma), double quotes, line feeds, and carriage returns in them.

I'm currently reading this material data into a DataTable and then attempting to write each record from this DataTable to a csv file.

Anyone have a function that can format a string to the correct format for MS Excel to align the columns correctly?

Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Does it need be output to a CSV file? It certainly can be done but rather then formatting each datarow & cells value I think it would be easuer just to output from a datatable to an Excel file (*.xls). You can do this with or without automatting Excel. I think its easier to do without but you loose some formatting options this way, such as sized columns, bolding fonts etc.

Public Sub ExportDataTableToExcel(ByVal dtSource As DataTable, ByVal strFile As String, Optional ByVal blnIncludeHeaderRow As Boolean = True)

        Dim strDbCon As String = ""

        If IO.File.Exists(strFile) Then IO.File.Delete(strFile)

        'Connection string to Excel file
        strDbCon = CreateExcelConnectionString(strFile, blnIncludeHeaderRow)

        Using con As New OleDbConnection(strDbCon)

            Dim bldrSql As New OleDbCommandBuilder
            Dim cmdCreateTable As New OleDbCommand
            Dim daXls As OleDbDataAdapter
            Dim dtTarget As New DataTable
            Dim strCreateTable As String = ""

            'Generate Create Table statement
            strCreateTable = CreateExcelTable(dtSource)

            'Create file and table structure
            With cmdCreateTable
                .Connection = con
                .CommandText = strCreateTable
            End With

            'Get table structure to generate insert statement
            daXls = New OleDbDataAdapter("Select * From [" & dtSource.TableName & "]", con)

            'Create Insert command
            bldrSql.DataAdapter = daXls
            daXls.InsertCommand = bldrSql.GetInsertCommand

            'Loop through each row and add to target dataset
            For Each rowSource As DataRow In dtSource.Rows
                Dim rowTarget As DataRow = Nothing

                rowTarget = dtTarget.NewRow

                'Loop thru each column
                For intIndex = 0 To dtSource.Columns.Count - 1
                    rowTarget.Item(intIndex) = rowSource.Item(intIndex)
                Next intIndex

            Next rowSource

            'Export data to file
        End Using 'con

    End Sub
Private Function CreateExcelTable(ByVal dtCreate As DataTable) As String

        Dim bldrSql As New StringBuilder
        Dim intTotalCols As Integer = 0

        intTotalCols = dtCreate.Columns.Count

        'Begin Create Table statement
        bldrSql.Append("Create Table [")
        bldrSql.Append("] (")

        'Loop thru each of the source table's columns
        For Each col As DataColumn In dtCreate.Columns


            'Format Excel column datatypes to match source table
            Select Case col.DataType.Name
                Case "SByte", "Byte", "Int16", "Int32", "Int64", _
                     "Decimal", "Double", "Single"
                    bldrSql.Append(" Number, ")
                Case "Boolean"
                    bldrSql.Append(" Bit, ")
                Case "Char", "String"
                    bldrSql.Append(" Memo, ")
                Case "DateTime"
                    bldrSql.Append(" DateTime, ")
                Case Else
                    bldrSql.Append(" Text, ")
            End Select 'col.DataType.Name
        Next col

        'Remove extra comma from end
        bldrSql.Remove(bldrSql.Length - 2, 2)

        Return bldrSql.ToString

    End Function
Private Function CreateExcelConnectionString(ByVal strFile As String, Optional ByVal blnHeader As Boolean = True) As String

        Dim bldrCon As New OleDb.OleDbConnectionStringBuilder
        bldrCon("Provider") = "Microsoft.Jet.OLEDB.4.0"
        bldrCon("Data Source") = strFile

        'blnHeader specifies whether a header row is included or not
        'IMEX=1; - Tells the driver to read everything as intermixed text

        If blnHeader = True Then
            bldrCon("Extended Properties") = "Excel 8.0;HDR=YES"
            bldrCon("Extended Properties") = "Excel 8.0;HDR=NO"
        End If

        Return bldrCon.ConnectionString

    End Function


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
I fully agree that exporting to xls is better, but if you need cvs, you can find a nice example here:
Pace, I was looking at that example and it wouldnt take care of his formatting and wildcard/character problems. Also the use of concatenatting the same string variable in a loop in this example is ineffiecient. For every value that is concatenated and new string variable will be created in memory. If he does want to go this route, I would suggest replacing the myString variable with a string builder.
Cloud Class® Course: Microsoft Windows 7 Basic

This introductory course to Windows 7 environment will teach you about working with the Windows operating system. You will learn about basic functions including start menu; the desktop; managing files, folders, and libraries.

JMO9966Author Commented:
Thanks guys, it needs to be a csv file.
JMO9966Author Commented:
Thanks guys, I created my own code to do so, but I will take a look at the last article mentioned.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.