Creating an import filter by type

Typical process of loading a document and populating an in-memory document model involves the following steps:

  1. create a document model instance,

  2. wrap it in a factory instance that implements the import_factory interface,

  3. create an import filter instance and pass the factory instance to it, and

  4. load the file using the filter.

You can create an import filter instance in one of two ways. The first is to use the orcus::create_filter() function and pass the desired format type, while the second is to instantiate a filter class directly, such as orcus::orcus_ods for loading an ODS document.

First, we are going to illustrate how to use the orcus::create_filter() function. Let’s include the necessary headers first:

#include <orcus/format_detection.hpp>  // for create_filter()

#include <orcus/spreadsheet/factory.hpp>
#include <orcus/spreadsheet/document.hpp>

#include <filesystem>

namespace fs = std::filesystem;

We also define the namespace alias fs for brevity.

As in the previous example, we read an environment variable named TESTDIR that points to the top-level test directory of this project repository:

const char* testdir = std::getenv("TESTDIR");

and construct the path to a test file, storing it in filepath:

auto filepath = fs::path{testdir} / "ods" / "autofilter" / "text-comparisons.ods";

Next step is to create a document model instance and wrap it in a factory instance:

orcus::spreadsheet::range_size_t ssize{1048576, 16384}; // sheet size
orcus::spreadsheet::document doc{ssize};
orcus::spreadsheet::import_factory factory(doc);

This creates a document instance and wraps it in a matching import_factory instance.

The final step is to create an import filter instance to load the document:

auto filter = orcus::create_filter(orcus::format_t::ods, &factory);
filter->read_file(filepath);

Here, orcus::format_t::ods specifies the filter type, and &factory passes the factory by pointer to create_filter().

Once created, call read_file() on the returned filter to load the document.

In comparison, if you want to create a filter instance by specifying its class directly, here is how to do it:

orcus::orcus_ods filter{&factory};
filter.read_file(filepath);

Since this example loads an ODS document, we instantiate orcus::orcus_ods directly and call read_file() to load it.

Orcus provides the following concrete filter types, each corresponding to a orcus::format_t enumerator: