0

我正在使用 C# 创建一个包含 200 个标题的 CSV 文件。我从另一个包含 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
    }
}
4

2 回答 2

2

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

我对你期望从哪里来Location和从哪里来感到困惑DateOfBirth。无论它在哪里,它都不会在您的值数组中。

于 2013-10-24T11:21:07.550 回答
0

从包含 3 列的文件中读取数据。然后从另一个文件中读取 Locality 和 DateOfBirth 值。清除第一个文件,然后将它们全部写入一个新的 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 个值。

读取第二个文件并获取其他值。对于第一个 List 中的每个值,在第二个 List 中找到相应的项目。然后使用这两个字符串数组列表写入一个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]));
    }
}
于 2013-10-24T11:41:02.520 回答