我是第一次使用 CSVhelper。另一个程序正在导出一个 csv 文件,文件看起来像这样
,"Employee","Earnings 1/Rate","Note"
,"John Doe","Regular 10.50", "Started Sep 1"
问题是我一开始就有一个空白列要处理。我不希望用户必须使用 excel 删除列才能使用该文件。那么我怎样才能忽略第一列或将列添加到我的数据表中。
错误(见程序底部附近的注释行)是 csv 文件中不存在字段空白
我的数据阅读课
namespace PayRateTracker
{
public class TestRecord
{
public string Blank { get; set; }
public string Employee {get; set;}
public string Earning { get; set; }
public string Note { get; set; }
}
public class MyClassMap : CsvClassMap<TestRecord>
{
public override void CreateMap()
{
Map(m => m.Blank).Index(0);
Map(m => m.Employee).Index(1);
Map(m => m.Earning).Index(2);
Map(m => m.Note).Index(3);
}
}
}
我有一条评论是错误发生在底部附近
namespace PayRateTracker
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
//Stream reader will read test.csv file in current folder
StreamReader sr = new StreamReader(@"G:\2013-09-20.csv");
//Csv reader reads the stream
CsvReader csvread = new CsvReader(sr);
//csvread will fetch all record in one go to the IEnumerable object record
IEnumerable<TestRecord> record = csvread.GetRecords<TestRecord>();
//foreach (var rec in record) // Each record will be fetched and printed on the screen
//{
// lblDisplay.Text = (string.Format("Name : {0}, Amount : {1}, Notes : {2} <br/>", rec.Employee, rec.Earning, rec.Note));
//}
sr.Close();
}
private void button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
using (var stream = File.OpenRead(@"G:\Test.csv"))
{
using (var reader = new StreamReader(stream))
{
using (var csvReader = new CsvReader(reader))
{
csvReader.Configuration.RegisterClassMap<MyClassMap>();
int i = 0;
while (csvReader.Read())
{
if (csvReader.FieldHeaders[0] == "")
{
csvReader.FieldHeaders[0] = "Blank";
}
if (i == 0)
{
foreach (var field in csvReader.FieldHeaders)
{
dt.Columns.Add(field);
}
}
DataRow row = dt.NewRow();
foreach (var field in csvReader.FieldHeaders)
{
row[field] = csvReader.GetField(field); // <-- Error here
}
dt.Rows.Add(row);
i += 1;
}
}
}
}
//return dt;
dataGridView1.DataSource = dt;
}
}
}