3

我使用库CsvHelper来编写 CSV。我有一个不包含所有记录的对象,我必须在我的 CSV 中添加空字段。例如:

public class Example
{
   public string Test1 { get; set; }
   public string Test2 { get; set; }
}

用这张地图:

public class ExampleMap : ClassMap<Example>
{
    public ExampleMap()
    {
      Map(ex=>ex.Test1).Index(0);
      Map(ex=>ex.Test2).Index(4);
    }
}

我想拥有这个对象

new Example() { Test1="dummy", Test2="field" };

这个 csv 结果:

dummy;;;field

我真的很努力解决这个问题,如果有人可以帮助我:) 非常感谢

4

4 回答 4

0

看起来违反了在两者之间具有显式列映射的概念。

CsvHelper 库似乎不支持这种情况,因为该库仅使用按升序排列的索引定义列映射(“映射列”)。

但是,如果确实需要有这样的输出,可以按如下方式引入“未使用”(保留)列:

internal sealed class Example
{
    public string Test1 { get; set; }
    public string Test2 { get; set; }

    public string Reserved1 { get; set; }
    public string Reserved2 { get; set; }
}

internal sealed class ExampleMap : CsvClassMap<Example>
{
    public ExampleMap()
    {
        Map(ex => ex.Test1).Index(0);
        Map(ex => ex.Reserved1).Index(1);
        Map(ex => ex.Reserved2).Index(2);
        Map(ex => ex.Test2).Index(3);
    }
}
于 2014-09-11T20:01:11.837 回答
0

我终于选择直接编辑每一行的最终 csv 字符串......它有效,但它很难看!

于 2014-09-11T22:44:42.790 回答
0

使用常量值定义 ClassMap 中的字段将允许您定义空列。这将生成带有标题的所需输出。

public class ExampleMap: ClassMap<Example>
{
     public ExampleMap()
     {
         Map(ex=>ex.Test1).Index(0).Name("Test1");
         Map().Index(1).Name("First Empty Column").Constant("");
         Map().Index(2).Name("Second Empty Column").Constant("");
         Map().Index(3).Name("Third Empty Column").Constant("");
         Map(ex=>ex.Test2).Index(4).Name("Test2");
     } 
}
于 2021-08-29T14:31:00.103 回答
0

Constant()注意:在较新的版本中,这可能会被运营商取代。

一种更加 API 一致的方法可能是使用自定义的ITypeConverter. 这是我的使用方法:

Map(i => i.SomeUnusedId).Name("SomeId").TypeConverter<EmptyConverter>(); //converst to an empty string

那么转换器可能如下所示:

public class EmptyConverter : ITypeConverter {
    /// <inheritdoc />
    public bool CanConvertFrom(Type type) {
        return true;
    }

    /// <inheritdoc />
    public bool CanConvertTo(Type type) {
        return true;
    }

    /// <inheritdoc />
    public object ConvertFromString(TypeConverterOptions options, string text) {
        return string.Empty;
    }

    /// <inheritdoc />
    public string ConvertToString(TypeConverterOptions options, object value) {
        return string.Empty;
    }
}
于 2020-06-10T16:03:59.877 回答