本文介绍了如何写唯一入选的类字段为CSV与CsvHelper?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用 CsvHelper 读写CSV文件,它是伟大的,但我不知道怎么写只是选择的类型的字段。

I use CsvHelper to read and write CSV files and it is great, yet I don't understand how to write only selected type fields.

假设我们有:

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;
        }
    }
}

和我们想排除数量 CsvField 日起,我们通过目前产生类似CSV文件:

and we wanted to exclude "Quantity" CsvField from resulting CSV file that we currently generate via something like:

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排除类型的字段?

What could I use to dynamically exclude a type field from the CSV?

如果这是我们可以处理生成的文件有必要,但我不知道如何删除整个CSV柱 CsvHelper

If it is necessary we could process the resulting file, yet I do not know how to remove an entire CSV column with CsvHelper.

推荐答案

你可以这样做:

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);
    }
}

我们正迫使创建的属性映射,然后修改它,动态地去除列。

We are forcing the creation of the attribute mapping and then modifying it, removing the column dynamically.

这篇关于如何写唯一入选的类字段为CSV与CsvHelper?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 15:02