var records = new List<Student>
{
new Student { ID = 1, Name = "Tom" },
new Student { ID = 2, Name = "Jerry" },
};
using (var writer = new StreamWriter("malema-student.csv"))
{
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
csv.WriteRecords(records);
}
}
通常在数据量不大的情况下我们就直接用这种就OK了。 List里面的内容太多。我们不能或者不好一次性放入内存的我们会用下面的方式来写入。
using (var writer = new StreamWriter("student-malema.csv"))
{
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
csv.WriteHeader<Student>();
foreach (var record in records)
{
csv.NextRecord();
csv.WriteRecord(record);
}
}
}
using (var writer = new StreamWriter("student-malema.csv"))
{
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
csv.WriteHeader<Student>();
foreach (var record in records)
{
csv.NextRecord();
csv.WriteField(record.ID);
csv.WriteField(record.Name);
}
}
}
注意要用using 或者手动调用 Dispose方法。 不然的话可能有些记录会没有写入到文件。