Skip to content

Read list of DTO

nambach edited this page Nov 15, 2021 · 2 revisions

The component to read data is ReaderConfig<T>. It holds rules to map each column into the corresponding field of class <T>.

Rules can be configured either based on column index or based on column title. If you want to base on title, index of title row must be provided via .titleAtRow(int)

ReaderConfig<Book> readerConfig = ReaderConfig
        .fromClass(Book.class)
        .titleAtRow(0) // provide title row index
        .dataFromRow(1)
        .column(0, "ibsn") // configure by column index
        .column(1, "title")
        .column("Date", "firstPublished") // by column title
        .column("Book genre", "subCategory")
        [...]

You can retrieve the config from the existing DataTemplate<T> as below.

DataTemplate<T> bookTemplate = ...

ReaderConfig<Book> readerConfig = bookTemplate.getReaderConfig();

The config provides 2 options: reading a single sheet as a list or reading multiple sheets as a map of lists.

InputStream stream = FileUtil.readFromDisk(".../book.xlsx");

// Read a single sheet
Result<Book> books = readerConfig.readSheet(stream);
for (Book book : books) {
    // Result<Book> is iterable
}

// Read multiple sheets
Map<String, Result<Book>> bookMap = readerConfig.readAllSheets(stream);
bookMap.forEach((sheetName, bookList) -> {
    for (Book book : bookList) {
        // ...
    }
});

For a more flexible way to read data, use the built-in .handler() as below.

ReaderConfig<Book> READER_CONFIG = ReaderConfig
    .fromClass(Book.class)
    .titleAtRow(0)
    .dataFromRow(1)
    .column(0, "ibsn")
    .column(1, "title")
    .handler(set -> set.atColumn(2)
                       .handle((book, cell) -> {
                           String value = cell.readString();
                           book.getCategory().setName(value);
                       }))
    .handler(set -> set.fromColumn(3)
                       .handle((book, cell) -> {
                           String title = cell.getColumnTitle();
                           if (title.contains("Rating in")) {
                               String year = title.substring(10);
                               Double rating = cell.readDouble();
                               book.setRating(year, rating);
                           }
                       }));