更改CSV文件列名称 [英] Change CSV file column name
本文介绍了更改CSV文件列名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个CSV文件,其中包含四列,即姓名,姓氏,年龄,出生数据
I have a CSV file which contains four columns i.e Name, Surname, Age, Data of Birth
我想将名称"列更改为全名".请问如何在C#中完成此操作?
I want to change the column Name to FullName. How can this be done in c# please?
var reader = new StreamReader(File.OpenRead(@"C:\myCSV.csv"));
var line = reader.ReadLine();
var values = line.Split(';');
var title = line.Split(',');
Console.WriteLine(title[0]);
if (title.Contains("Name"))
{
title[0] = "FullName";
}
现在,我被困在如何继续更改列名的问题上
Now I'm stuck on how should I continue to change the Column name
推荐答案
如果您尝试创建一个3列而不是4列的新文件,这将是一个起点,但是,您应该使用csv解析器.这只是一个示范,向您展示如何组合两列.
If you are attempting to create a new file with 3 columns instead of 4 this would be a starting point, however, you should use a csv parser. This is just a demonstration to show you how to combine the two columns.
string[] lines = System.IO.File.ReadAllLines(@"C:\myCSV.csv");
using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\myCSV2.csv"))
{
foreach (string line in lines)
{
if (line==lines[0])
{ //Change Header
file.WriteLine("Fullname,Age,Date of Birth");
}
else
{
string[] values = line.Split(',');
file.WriteLine(string.Format("{0} {1},{2},{3}",
values[0],values[1],values[2],values[3]));
}
}
}
这篇关于更改CSV文件列名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文