fantails
fantails

Reputation:

How do I save a 2-dimensional array as a csv file?

I am using visual studio 8. vb.net. I have an array, array1(100,8) and I want to save it as a csv file so that I can open it in excel and examine the contents more closely. The feature, of saving as a csv file, is not going to form an integral part of the finished vb app, I just need something quick and dirty because the data in the array just requires looking at in excel so that I can fully understand its significance and thus continue coding my app.

Thank you for all and any help you can give.

Upvotes: 1

Views: 7872

Answers (2)

Marc Gravell
Marc Gravell

Reputation: 1063864

Untested C#:

    static void WriteCsv<T>(T[,] data, string path)
    {
        char[] specialChars = {',','\"', '\n','\r'};
        using (var file = File.CreateText(path))
        {
            int height = data.GetLength(0), width = data.GetLength(1);
            for (int i = 0; i < height; i++)
            {
                if (i > 0) file.WriteLine();
                for (int j = 0; j < width; j++)
                {
                    string value = Convert.ToString(data[i, j]);
                    if (value.IndexOfAny(specialChars) >= 0)
                    {
                        value = "\"" + value.Replace("\"", "\"\"")
                            + "\"";
                    }
                    if (j > 0) file.Write(',');
                    file.Write(value);
                }
            }
        }
    }

Which reflector translates as:

Private Shared Sub WriteCsv(Of T)(ByVal data As T(0 To .,0 To .), ByVal path As String)
    Dim specialChars As Char() = New Char() { ","c, """"c, ChrW(10), ChrW(13) }
    Using file As StreamWriter = File.CreateText(path)
        Dim height As Integer = data.GetLength(0)
        Dim width As Integer = data.GetLength(1)
        Dim i As Integer
        For i = 0 To height - 1
            If (i > 0) Then
                file.WriteLine
            End If
            Dim j As Integer
            For j = 0 To width - 1
                Dim value As String = Convert.ToString(data(i, j))
                If (value.IndexOfAny(specialChars) >= 0) Then
                    value = ("""" & value.Replace("""", """""") & """")
                End If
                If (j > 0) Then
                    file.Write(","c)
                End If
                file.Write(value)
            Next j
        Next i
    End Using
End Sub

Upvotes: 2

Nader Shirazie
Nader Shirazie

Reputation: 10776

I don't have a vb compiler on me, but maybe this pseudocode will help

textStream = File.OpenText("c:\output.csv")
for i = 0 to 99
{
  for j = 0 to 7
  {
    write array1[i][j] to textStream
    write "," to textStream
  }
  write newline to textStream
}
close textstream

Next, open the file in excel.

Upvotes: 0

Related Questions