在 C# 中比较和创建 CSV 文件

本文关键字:创建 CSV 文件 比较 | 更新日期: 2023-09-27 18:36:47

我正在使用C#创建一个CSV文件,其中包含200个标头。我正在从另一个包含 150 个标头的 CSV 文件中获取数据。我的问题是我将如何根据其标题放置数据。例如,我在下面给出和示例。

将使用 C# 创建的 CSV 文件:

Name, Surname, Locality, DateOfbirth, Age
Joe,  Smith,                          60
Sam,  Brown,                          20

从中获取数据的 CSV

Name, Surname, Age
Joe,  Smith,   60
Sam,  Brown,   20

这是一个示例代码(实际文件包含 150 个标头,新的 CSV 文件包含 200 个标头)

string[] lines = System.IO.File.ReadAllLines(fileUrl);
using (System.IO.StreamWriter file = new System.IO.StreamWriter(fileUrl))
{
    foreach (string line in lines)
    {
        if (line == lines[0])
        {   
            //Changing the header of the first file
            file.WriteLine("Name, Surname, Locality, DateOfBirth, Age");
        }
        else
        {
            string[] values = line.Split(',');
            file.WriteLine(string.Format("{0},{1},{2},{3},{4}",
                                values[0], values[1], values[2], values[3], values[4]));
        } //exception being thrown here since the array is out of range
    }
}

在 C# 中比较和创建 CSV 文件

您只从输入文件中读取三列,但正在尝试写出五列。所以values[3]values[4]将超出范围。

我很困惑你期望从哪里获得LocationDateOfBirth。无论它在哪里,它都不会在您的值数组中。

从包含 3 列的文件中读取数据。然后从另一个文件中读取"位置"和"出生日期"值。清除第一个文件,然后将它们全部写入新的 csv 文件中。

    public static List<string[]> Parse(string Path)
    {
        List<string[]> Parsed = new List<string[]>();
        using (StreamReader Reader = new StreamReader(Path))
        {
            string Line;
            char Seperator = ',';
            while ((Line = Reader.ReadLine()) != null)
            {
                if (Line.Trim().StartsWith("//")) continue;
                if (string.IsNullOrWhiteSpace(Line)) continue;
                string[] Data = Line.Split(Seperator);
                Parsed.Add(Data);
            }
        }
        return Parsed;
    } 

您可以使用上述方法从 CSV 文件中读取。想象一下,您读取第一个文件并得到 List,字符串数组有 3 个值。

读取第二个文件并获取其他值。对于第一个列表中的每个值,在第二个列表中查找相应的项目。然后使用这两个字符串数组列表写入 csv 文件。

List<string[]> File1 = Parse("File1Path");
List<string[]> File2 = Parse("File2Path");
using (System.IO.StreamWriter file = new System.IO.StreamWriter(OutputFile))
{
   // write header first:    
   file.WriteLine("Name, Surname, Locality, DateOfBirth, Age");
   foreach (string line in File1)
   {
     var found = File2.Where(x => x[0] == line[0]).FirstOrDefault();         
     if(null == found) continue;
     file.WriteLine(string.Format("{0},{1},{2},{3},{4}",
                                line[0], line[1], found[3], found[4], line[2]));
    }
}