我正在使用CsvHelper库将csv文件转换为另一个具有不同结构的csv文件。首先,我将csv文件的内容读入数据表并显示在DataGridView上,一切都运行良好。
我在将DataTable的内容导出到新的csv文件时遇到问题。由于某种原因,不会导出DataTable末尾的某些行。我认为它与StreamWriter类有关,但我找不到原因。
我使用Sharpdevelop。
//Read the original CSV file
void Button1Click(object sender, EventArgs e)
{
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK) {
StreamReader str = new StreamReader(openFileDialog1.FileName);
CsvReader csvReadFile = new CsvReader(str);
dt = new DataTable();
dt.Columns.Add("Value", typeof(int));
dt.Columns.Add("Time Stamp", typeof(DateTime));
while (csvReadFile.Read()) {
var row = dt.NewRow();
foreach (DataColumn column in dt.Columns) {
row[column.ColumnName] = csvReadFile.GetField(column.DataType, column.ColumnName);
}
dt.Rows.Add(row);
}
dataGridView1.DataSource = dt;
}
}
//Write the new CSV file
void SaveButtonClick(object sender, EventArgs e)
{
DialogResult result = saveFileDialog1.ShowDialog();
if (result == DialogResult.OK) {
StreamWriter stw = new StreamWriter(saveFileDialog1.FileName);
CsvWriter csvWrite = new CsvWriter(stw);
foreach (DataRow row in dt.Rows) {
for (var i = 0; i < dt.Columns.Count; i++) {
csvWrite.WriteField(row[i]);
}
csvWrite.NextRecord();
}
}