Skip to content

CSV data context

CSV data contexts allow exposing one or more CSV files as tables. To add a CSV data context to your project, use the context menu command as shown below.

Datacontext CSV add menu

This will create a new data context script and scaffold code for a custom CSV data context class. To register CSV files as tables, you must implement the Configure method.

For example:

1
2
3
4
5
6
7
8
public class CSVDataContext1 : CsvDataContext 
{
    protected override void Configure(CsvContextConfiguration config)
    {
        config.AddFile(@"C:\path\to\data_file.csv", ",");
        config.AddFile(@"C:\path\to\data_file2.csv", ",", "more_data");
    }
}

The arguments of the AddFile method are:

  • path to the CSV file
  • separator
  • name of the table (optional, if not specified, file name is used)

After running the script, two tables will be exposed by the data context. These tables can then be used by both scripts and other project code.

Loaded tables

Column types

By default, the data type for all columns is string. This can be overridden by using the ConfigureColumn method.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
public class CSVDataContext1 : CsvDataContext 
{
    protected override void Configure(CsvContextConfiguration config)
    {
        config.AddFile(@"C:\path\to\data_file.csv", ",");

        config
            .AddFile(@"C:\path\to\data_file2.csv", ",", "more_data")
            .ConfigureColumn<int>("Run count")
            .ConfigureColumn<DateTime?>("Last Run Date");
    }
}

Once the script is executed, the data context will be updated to use the specified column types.

CSV table col types

Using relative paths

In workbook apps, you can look up the current workbook path in order to use csv files that are in the same directory as the workbook.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class CSVDataContext1 : CsvDataContext 
{
    private readonly IWorkbookAccessor workbookAccessor;

    public CSVDataContext1(IWorkbookAccessor workbookAccessor)
    {
        this.workbookAccessor = workbookAccessor;
    }

    protected override void Configure(CsvContextConfiguration config)
    {
        string wbPath = this.workbookAccessor.Workbook.Path;

        // we're expecting a "more_data.csv" file to be in the 
        // same folder as the workbook
        var csvPath = Path.Combine(wbPath, "more_data.csv");

        config
            .AddFile(csvPath, ",", "more_data")
            .ConfigureColumn<int>("Run Count")
            .ConfigureColumn<DateTime?>("Last Run Date");
    }
}

Combining with workbook data

In workbook apps, you might want to use both the workbook data context as well as a CSV data context to access data in External CSV files. This is enabled out of the box as context definition scripts will add the types they generate into the DataContextTypes list in the project.config file without removing the types generated by other scripts.

CSV table col types