【问题标题】:How do I write data column b y column to a csv file如何将数据列逐列写入 csv 文件
【发布时间】:2014-06-25 09:16:06
【问题描述】:

我在将一些数据写入 csv 文件时遇到了一个大问题。我有很多测量值。每个值都由名称、单位、值描述。所以我想为每个值构建一个具有这三个属性的列。 我想像这样将它存储到 csv 文件中:

Width    Cell Wall Thickness   Coarseness   Curl-Index    etc.
mm           mm                    mg/m         %         etc.
16,2         3,2                  0,000       11,7        etc.

到目前为止,我正在为名称编写一个标题,另一个用于单位和值(之前存储在字符串数组中),我只是写在一行中。 到目前为止,我的 csv 文件看起来像这样:(

Width;Cell Wall Thickness;Coarseness;Curl-Index;etc.
mm;mm;mg/m;%;etc.
16,2;3,2;0,000;11,7;etc.

如果值不多,我不会在意这个,但是有很多,所以当我打开 csv 文件时,会出现标题不适合值和单位的问题。它没有组织,我无法将值与标题匹配。 我希望所有内容都按列组织。任何帮助将不胜感激! 这是我到现在为止的代码:

StreamWriter sw = new StreamWriter("test2.csv");
    int RowCount = 3;
    int ColumnCount = 4;
string[][] Transfer_2D = new string[RowCount][];
Transfer_2D[0] = new string[3]{"Width", "CWT", "Coarseness", "Curl-Index"};//name of the values
Transfer_2D[1] = new string[3] {"mm", "mm", "mg/m", "%"};   //units
Transfer_2D[2] = new string[3] { TransferData[0], TransferData[1], TransferData[2],    TransferData[3] };
for (int i = 0; i < RowCount; i++)
    {
        for (int j = 0; j < ColumnCount; j++)
        {
            sw.Write(Transfer_2D[i][j]);//write one row separated by columns
            if (j < ColumnCount)
            {
                sw.Write(";");//use ; as separator between columns
            }
        }
        if (i < RowCount)
        {
            sw.Write("\n");//use \n to separate between rows
        }
    }

    sw.Close();

 }

【问题讨论】:

  • 能否用;, 编辑“预期”结果,最好能提供少量样本数据
  • CSV 文件并不意味着“好”。它旨在供机器使用,但也可供人类理解和编辑。易于阅读不是 csv 文件的问题。如果您希望人们轻松阅读文件,则必须选择其他格式。例如 HTML,使用网络浏览器。

标签: c#


【解决方案1】:

您可以将字符串设置为固定长度。 示例看这里:(.NET Format a string with fixed spaces)

int iWantedStringLength = 20;

string sFormatInstruction = "{0,-" + iWantedStringLength.ToString() + "}";

for (int i = 0; i < RowCount; i++)
    {
        for (int j = 0; j < ColumnCount; j++)
        {
            sw.Write(String.Format(sFormatInstruction, Transfer_2D[i][j]));//write one row separated by columns
            if (j < ColumnCount)
            {
                sw.Write(";");//use ; as separator between columns
            }
        }
        if (i < RowCount)
        {
            sw.Write("\n");//use \n to separate between rows
        }
    }

【讨论】:

    【解决方案2】:

    对于 CSV 工作,我使用 http://joshclose.github.io/CsvHelper/,这是一个非常好的帮助类,但它需要你稍微改变你的工作。

    我建议您创建一个类来存储每个条目,然后创建一个“映射器”将其映射到 csv 字段。然后,您可以将一组对象和您的映射类传递给助手,它会生成结构化的 CSV。

    该页面上有很多示例,因此您应该可以直接完成。

    【讨论】:

      猜你喜欢
      • 2012-12-17
      • 2020-06-01
      • 2022-01-09
      • 2018-06-15
      • 1970-01-01
      • 2019-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多