Search code examples
c#.netcsvexport-to-csvcsvhelper

Add dummy empty fields in CSVHelper


I use the library CsvHelper to write CSV. I have object which doesn't contain all the records and I have to add empty fields to my CSV. For instance:

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

with this map:

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

and i'd like to have for this object

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

this csv result:

dummy;;;field

I really struggle with this problem, if someone can help me :) Many thanks


Solution

  • Note: This might be superseded by the Constant() operator in newer versions.

    A more API-consistent approach might be to use a custom ITypeConverter. Here is how I use it:

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

    Then the converter might look like this:

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