我正在使用 CSVHelper 从我的数据网格视图中读取和写入 csv 文件。
我可以读取 csv 文件,但是当我写它时,它会列出同一行的标题和行。
如何在 excel 中将行放在不同的行中?
private void btnWrite_Click(object sender, EventArgs e)
{
using (SaveFileDialog sfd = new SaveFileDialog() { Filter = "CSV|*.csv", ValidateNames = true })
{
if (sfd.ShowDialog() == DialogResult.OK)
{
using (var sw = new StreamWriter(sfd.FileName))
{
var csvwriter = new CsvWriter(sw, CultureInfo.CurrentCulture);
csvwriter.WriteHeader(typeof(Student));
foreach (Student s in studentBindingSource.DataSource as List<Student>)
{
csvwriter.WriteRecord(s);
csvwriter.Flush();
}
}
MessageBox.Show("Data has been saved", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
感谢任何帮助,在此先感谢您。
如果你是手动写单条记录(
WriteRecord
而不是WriteRecords
),或者手动写表头(WriteHeader
),那么你需要手动去下一条记录
var csvwriter = new CsvWriter(sw, CultureInfo.CurrentCulture);
csvwriter.WriteHeader(typeof(Student));
csvwriter.NextRecord(); // < ---- this
foreach (Student s in studentBindingSource.DataSource as List<Student>)
{
csvwriter.WriteRecord(s);
csvwriter.NextRecord(); // < ---- this
}
阅读更多内容CSVHelper 的文档页面.
WriteHeader 不会让你前进到下一行。将 NextRecord 与 WriteHeader 分开允许您在需要时在标头中写入更多内容。 WriteRecord 也不会让您前进到下一行,让您能够写入多个对象或使用 WriteField 写入单个字段。
旁注,我建议您向
using
变量添加一个 csvwriter
块/语句,这样它就会自动正确地刷新。
private void btnWrite_Click(object sender, EventArgs e)
{
using (SaveFileDialog sfd = new SaveFileDialog() { Filter = "CSV|*.csv", ValidateNames = true })
{
if (sfd.ShowDialog() == DialogResult.OK)
{
using (var sw = new StreamWriter(sfd.FileName))
{
var csvwriter = new CsvWriter(sw, CultureInfo.CurrentCulture);
csvwriter.WriteRecords<Student>(s);
}
MessageBox.Show("Data has been saved", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}