Writing data from a 2D String Array to a csv file using VB.NET

VB.NET , csv , Array South Africa
  • 11 years ago

    This is a simple piece of code for writing data from a two dimensional string array to a comma delimited file for easy reading into excel.

        Sub TwoDArrayToCSV(ByVal DataArray(,) As String)
            Dim str As String = ""
            Dim ofile As String = ""
    
            svDialog("csv|*.csv", "save as...", ofile)
            Dim sw As System.IO.StreamWriter = New System.IO.StreamWriter(ofile)
    
            For i As Int32 = DataArray.GetLowerBound(0) To DataArray.GetUpperBound(0)
                For j As Int32 = DataArray.GetLowerBound(1) To DataArray.GetUpperBound(1)
                    str += DataArray(i, j) + ","
                Next
                sw.WriteLine(str)
                str = ""
            Next
            sw.Flush()
            sw.Close()
        End Sub
    
        Sub svDialog(ByVal infilter As String, ByVal dtitle As String, ByRef outfile As String)
            Dim openFileDialog1 As New SaveFileDialog()
            With openFileDialog1
                .Filter = infilter
                .FilterIndex = 1
                .Title = dtitle
                .DefaultExt = Strings.Right(infilter, 3)
                .ShowDialog()
                outfile = openFileDialog1.FileName
                .RestoreDirectory = True
          End With
        End Sub
    

Post a reply

No one has replied yet! Why not be the first?

Sign in or Join us (it's free).

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Hofstadter's Law: It always takes longer than you expect, even when you take into account Hofstadter's Law.”