如何将二维数组保存为csv文件?

时间:2009-08-30 07:22:42

标签: vb.net csv

我正在使用visual studio 8. vb.net。 我有一个数组,array1(100,8),我想将其保存为csv文件,以便我可以打开它 擅长并更仔细地检查内容。保存为csv文件的功能不会成为完成的vb应用程序的一个组成部分,我只需要快速和脏的东西,因为数组中的数据只需要在excel中查看,以便我可以完全理解它重要性因此继续编码我的应用程序。

感谢您提供所有帮助和任何帮助。

2 个答案:

答案 0 :(得分:2)

未经测试的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);
                }
            }
        }
    }

哪个反射器翻译为:

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

答案 1 :(得分:0)

我没有vb编译器,但也许这个伪代码会有帮助

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

接下来,在excel中打开文件。