【问题标题】:Add a column to a CSV and merge to columns to this new column将列添加到 CSV 并将列合并到此新列
【发布时间】:2020-03-30 03:45:15
【问题描述】:

我有一个这样的 CSV 文件:

Header1;Header2;Header3;Header4;Header5;Header6
abc;123;xyz;...;...;...

我想在这个 csv 的末尾添加一个新列,并在这个新列中直接合并第 1+2 列:

Header1;Header2;Header3;Header4;Header5;Header6;Header7
abc;123;xyz;...;...;...;abc123

我可以添加一个新列,但是如何添加数据?

这是我正在使用的:

static void Main(string[] args)
{
    String filePath = @"C:/Data.csv";

    var csv = File.ReadLines(filePath)
      .Select((line, index) => index == 0
         ? line + ";ExtID"
         : line + ";" + line.ToString())
      .ToList();

    File.WriteAllLines(filePath, csv);
}

【问题讨论】:

  • 就个人而言,我永远不会敢于自己进行 CSV 解析。使用众多CSV reading libraries 之一应该是要走的路。

标签: c# csv merge


【解决方案1】:

如果您有 简单 csv(没有 引号),您可以尝试 Linq:添加标题或 Split 行和 @987654322 @2物品Taken来自它:

  ...

  var csv = File
    .ReadLines(filePath)
    .Select((line, index) => index == 0 
       ? line + ";ExtID"                                     // Extra header
       : line + ";" + string.Concat(line.Split(';').Take(2)) // first two items added
     )
    .ToList();

  File.WriteAllLines(filePath, csv);

【讨论】:

    【解决方案2】:

    无 LINQ 方法

            string filePath = @"C:/Data.csv";
            var lines = File.ReadLines(filePath).ToList();
    
            // Add new Column
            var newColumn = ";Header7";
            lines[0] = lines[0] += newColumn;
    
            // Adds items to the new column
            for (int index = 1; index < lines.Count; index++)
            {
                var rowItems = lines[index].Split(';');
                lines[index] = $"{lines[index]};{rowItems[0]}{rowItems[1]}";
            }
    
            File.WriteAllLines(filePath, lines);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-21
      • 2018-02-06
      • 2012-08-31
      • 2021-04-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-23
      • 1970-01-01
      相关资源
      最近更新 更多