嗨,我有3个CSV文件,想要将它们组合起来

时间:2016-04-29 10:03:02

标签: c# winforms csv c#-4.0

要合并为一个文件的N个CSV文件。并且数据必须并排存在,像这样的东西

DatTime_M1  Voltage Currency| Dattime_m2 Volage currency |.....DatTime_N Vol  Curr
2016-04-29  237.1   3.54    2016-04-29  237.1   3.54   2016-04-29   237.1   3.54
2016-04-29  237.7   3.54   2016-04-29   237.1   3.54   2016-04-29   237.1   3.54
2016-04-29  236.4   3.54    2016-04-29  237.1   3.54   2016-04-29   237.1   3.54
2016-04-29  236.4   3.53    2016-04-29  237.1   3.54   2016-04-29   237.1   3.54

我编写了一个代码,而不是上面的合并,只需简单地合并或追加到同一行。

string[] files = (Directory.GetFiles(txtConsolidated_OS_CSV.Text.Trim()));
                    foreach (var file in files)
                    {
                        StringBuilder sb = new StringBuilder();
                        string filename = Path.GetFileNameWithoutExtension(file);
                        if (file.EndsWith(".csv"))
                        {
                            string[] rows = File.ReadAllLines(file);
                            for (int i = 0; i < rows.Length; i++)
                            {
                                if (i == 0)
                                {
                                    if (counter == 0)
                                    {
                                        sb.Append(rows[i] + "\n");
                                        counter++;
                                    }
                                }
                                else
                                {
                                    sb.Append(rows[i] + "\n");
                                }
                            }
                        }
                        string csvfile = txtConsolidated_OS_CSV.Text + "\\Merged_OS.csv";

                        if (File.Exists(csvfile))
                        {
                            File.AppendAllText(csvfile, sb.ToString());
                            sb.Clear();
                        }
                        else
                        {
                            File.WriteAllText(csvfile, sb.ToString());
                            sb.Clear();
                        }

1 个答案:

答案 0 :(得分:0)

使用LINQ:

var allCsv = Directory.EnumerateFiles("Src-Path", ".*csv", SearchOption.TopDirectoryOnly);
string[] header = 
{ 
    File.ReadLines(allCsv.First()).First(l => !string.IsNullOrWhiteSpace(l)) 
};

 // Get CSV Data
 var mergedData = allCsv.SelectMany(csv => File.ReadLines(csv).SkipWhile(l => string.IsNullOrWhiteSpace(l)).Skip(1)); 

 // skip header of each file
 File.WriteAllLines("Dest-Path", header.Concat(mergedData));

来自here