Community discussion forum

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

  • 4 months 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 was edited on 22/07/2009 11:58:51 Report abuse

Post a reply

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

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

Want to stay in touch with what's going on? Follow us on twitter!