如何将2维数组保存为csv文件? [英] How do I save a 2-dimensional array as a csv file?

查看:210
本文介绍了如何将2维数组保存为csv文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

推荐答案

谢谢大家的帮助,解决方案

解决方案

未测试的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

这篇关于如何将2维数组保存为csv文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆