我正在使用 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
}
}