我使用
CsvHelper
读取和写入CSV文件,这是伟大的,但我不明白如何只写选择的类型字段.
说我们有
@H_301_4@using CsvHelper.Configuration; namespace Project { public class DataView { [CsvField(Name = "N")] public string ElementId { get; private set; } [CsvField(Name = "Quantity")] public double ResultQuantity { get; private set; } public DataView(string id,double result) { ElementId = id; ResultQuantity = result; } } }我们想从我们目前通过以下类似的生成的CSV文件中排除“Quantity”CsvField:
@H_301_4@using (var myStream = saveFileDialog1.OpenFile()) { using (var writer = new CsvWriter(new StreamWriter(myStream))) { writer.Configuration.Delimiter = '\t'; writer.WriteHeader(typeof(ResultView)); _researchResults.ForEach(writer.WriteRecord); } }我可以用什么来动态地从CSV中排除类型字段?
解决方法
你可以这样做:
@H_301_4@using (var myStream = saveFileDialog1.OpenFile())
{
using (var writer = new CsvWriter(new StreamWriter(myStream)))
{
writer.Configuration.AttributeMapping(typeof(DataView)); // Creates the CSV property mapping
writer.Configuration.Properties.RemoveAt(1); // Removes the property at the position 1
writer.Configuration.Delimiter = "\t";
writer.WriteHeader(typeof(DataView));
_researchResults.ForEach(writer.WriteRecord);
}
}