Skip to content

2. Fluent Configuration

Jos de Weger edited this page Jan 1, 2019 · 3 revisions

There are two ways to configure SheetToObjects. Via fluent configuration or attributes on the model you are trying to map to. It is possible to setup multiple configurations, as long as the type you are mapping to is different.

Fluent Configuration

An example of configuring the SheetMapper using the fluent api:

var sheetMapper = new SheetMapper()
    .AddConfigFor<SomeModel>(cfg => cfg
        .MapColumn(column => column.WithHeader("First Name").IsRequired().MapTo(m => m.FirstName))
        .MapColumn(column => column.WithHeader("Last Name").IsRequired().MapTo(m => m.LastName)));

sheetMapper.Map<SomeModel>(data);

SheetMapper

On the SheetMapper you can add as many configurations as you want, which means that you can map different Types to different sheets in one application. When the actual mapping is done the appropriate configuration is used based on the Type passed as generic with the Map method.

MappingConfig options

HasHeaders

Indicates wether the first row of the sheet contains the headers

StopParsingAtFirstEmptyRow

Ensures that parsing is stopped as soon as the first empty row is encountered. Can save some time when parsing bigger sheets

MapColumn

Here, among other things, you can specify to what property of your class the column should be mapped. There are three ways you can identify the column:

WithHeader

Identify the column by specifying the header name

WithColumnIndex

Identify the column by specifying the colum index

WithColumnLetter

Identify the column by specifying the colum letter (for providers such as Excel, where columns are identified by column letter alphabetically, this might come in handy

WithDefaultValue

When no value is found, this default value will be used

WithRequiredInHeaderRow

Specified header has to exist in the header row, otherwise a validation error is returned

AddParsingRule

Rule that the column needs to adhere to during parsing of the value

AddRule

Rule that will be checked after parsing. See Validation for more details on predefined rules

AddCustomRule

A custom rule can be added, by defining a func that takes the Type as a param and returns a bool

ParseValueUsing

If you want to write your own parsing logic for parsing a specific column, use the Func in this method, e.g.:

MapColumn(column => column
    .WithHeader("TotalSales")
    .ParseValueUsing(x =>
    {
        if(x > 1000)
            return Color.Green;
        else if(x > 500)
            return Color.Orange;
        else
            return Color.Red;
    })

UsingFormat

Is used for parsing DateTime strings properly

For more information, check out the tests: https://github.com/josdeweger/SheetToObjects/blob/dev/src/SheetToObjects.Specs