?
Solved

Visual Basic.Net - CSV file formatting

Posted on 2010-03-28
6
Medium Priority
?
360 Views
Last Modified: 2012-05-09
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 vb.net 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?

Thanks
0
Comment
Question by:JMO9966
6 Comments
 
LVL 5

Accepted Solution

by:
Tommy11b earned 1000 total points
ID: 28913541
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
            con.Open()
            With cmdCreateTable
                .Connection = con
                .CommandText = strCreateTable
                .ExecuteNonQuery()
            End With
            con.Close()

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

            '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

                dtTarget.Rows.Add(rowTarget)
            Next rowSource

            'Export data to file
            daXls.Update(dtTarget)
        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(dtCreate.TableName)
        bldrSql.Append("] (")

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

            bldrSql.Append(col.ColumnName)

            '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)
        bldrSql.Append(")")

        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"
        Else
            bldrCon("Extended Properties") = "Excel 8.0;HDR=NO"
        End If

        Return bldrCon.ConnectionString

    End Function

0
 
LVL 4

Assisted Solution

by:Pacemaker9007
Pacemaker9007 earned 500 total points
ID: 28913869
I fully agree that exporting to xls is better, but if you need cvs, you can find a nice example here: http://vijirajkumar.blogspot.com/2009/06/export-dataset-to-csv-file-using-vbnet.html
0
 
LVL 5

Assisted Solution

by:Tommy11b
Tommy11b earned 1000 total points
ID: 28915010
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.
0
Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 

Author Comment

by:JMO9966
ID: 28915980
Thanks guys, it needs to be a csv file.
0
 
LVL 83

Assisted Solution

by:CodeCruiser
CodeCruiser earned 500 total points
ID: 29007641
0
 

Author Closing Comment

by:JMO9966
ID: 31708119
Thanks guys, I created my own code to do so, but I will take a look at the last article mentioned.
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Well, all of us have seen the multiple EXCEL.EXE's in task manager that won't die even if you call the .close, .dispose methods. Try this method to kill any excels in memory. You can copy the kill function to create a check function and replace the …
Introduction As chip makers focus on adding processor cores over increasing clock speed, developers need to utilize the features of modern CPUs.  One of the ways we can do this is by implementing parallel algorithms in our software.   One recent…
How can you see what you are working on when you want to see it while you to save a copy? Add a "Save As" icon to the Quick Access Toolbar, or QAT. That way, when you save a copy of a query, form, report, or other object you are modifying, you…
Get the source code for a fully functional Access application shell with several popular security features that Access VBA application developers desire, but find difficult or impossible to figure out how to code. You get the source code for managi…

601 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