C# 处理CSV文件
我正在使用C# 处理CSV文件,c#,file,csv,C#,File,Csv,我正在使用sebastienlorionCSV阅读器处理我的C#3.0版CSV文件 举例说明 id|name|dob (Header) 1|sss|19700101 (data) 2|xx|19700201 (data) 我的业务目标是 class Employee { public string ID {get;set;} public string Name {get;set;} public string Dob {get;set;} } 我读取CSV流并将其存储在
sebastienlorion
CSV阅读器处理我的C#3.0版CSV文件
举例说明
id|name|dob (Header)
1|sss|19700101 (data)
2|xx|19700201 (data)
我的业务目标是
class Employee
{
public string ID {get;set;}
public string Name {get;set;}
public string Dob {get;set;}
}
我读取CSV流并将其存储在列表中
如果我调用r[0]、r[1]、r[2]
我将得到“索引超出范围异常”
。如何处理列表以避免错误
编辑
对不起,我知道结果了。
当我处理
foreach (var q in col)
{
Employee emp=new Employee();
emp.ID =q[0];
emp.Name=q[1];
emp.Dob=q[2];
}
事情进展顺利。阅读此类读者的正确方法是,例如:
List<Employee> employees = new List<Employee>();
using (IDataReader csv = new CsvReader
(new StreamReader("D:\\sample.txt"), true, '|'))
{
while(csv.Read()) {
Employee emp = new Employee();
emp.ID = r.GetString(0); // or int.Parse(...) if it is an int
emp.Name = r.GetString(1);
emp.Dob = r.GetString(2); // or DateTime.Parse(...) if it is a DateTime
employees.Add(emp);
}
}
List employees=newlist();
使用(IDataReader csv=新CsvReader
(新的StreamReader(“D:\\sample.txt”),true,“|”)
{
而(csv.Read()){
员工emp=新员工();
emp.ID=r.GetString(0);//或int.Parse(…),如果它是int
emp.Name=r.GetString(1);
emp.Dob=r.GetString(2);//或DateTime.Parse(…),如果它是DateTime
添加(emp);
}
}
您也可以使用迭代器块,并且可以使用
GetDateTime
/GetInt32
,但我不能确定,所以我在上面使用了GetString
。您是在某些行还是所有行上都出现了错误?在忽略标题后,当我处理其余行时,请注意!当Jon Skeet和Marc Gravell在场时,你可以澄清任何事情
foreach (var q in col)
{
Employee emp=new Employee();
emp.ID =q[0];
emp.Name=q[1];
emp.Dob=q[2];
}
List<Employee> employees = new List<Employee>();
using (IDataReader csv = new CsvReader
(new StreamReader("D:\\sample.txt"), true, '|'))
{
while(csv.Read()) {
Employee emp = new Employee();
emp.ID = r.GetString(0); // or int.Parse(...) if it is an int
emp.Name = r.GetString(1);
emp.Dob = r.GetString(2); // or DateTime.Parse(...) if it is a DateTime
employees.Add(emp);
}
}