All Projects → nambach → ExcelUtil

nambach / ExcelUtil

Licence: Apache-2.0 license
Excel utility for Java to read and write data in declarative way.

Programming Languages

java
68154 projects - #9 most used programming language
Batchfile
5799 projects

Projects that are alternatives of or similar to ExcelUtil

simple-excel
Generate excel sheets in Java
Stars: ✭ 85 (+214.81%)
Mutual labels:  excel, poi
Excel4j
✨ Excel operation component based on poi & CSV ✨
Stars: ✭ 305 (+1029.63%)
Mutual labels:  excel, poi
ExcelReads
ExcelReads(简单Excel通用读写器)
Stars: ✭ 46 (+70.37%)
Mutual labels:  excel, poi
hadoopoffice
HadoopOffice - Analyze Office documents using the Hadoop ecosystem (Spark/Flink/Hive)
Stars: ✭ 56 (+107.41%)
Mutual labels:  excel, poi
Myexcel
MyExcel, a new way to operate excel!
Stars: ✭ 1,198 (+4337.04%)
Mutual labels:  excel, poi
npoi
a .NET library that can read/write Office formats without Microsoft Office installed. No COM+, no interop.
Stars: ✭ 4,493 (+16540.74%)
Mutual labels:  excel, poi
Poiji
🍬 A tiny library converting excel rows to a list of Java objects based on Apache POI
Stars: ✭ 255 (+844.44%)
Mutual labels:  excel, poi
excel2javabeans
convert excel rows to javabeans and vice visa
Stars: ✭ 16 (-40.74%)
Mutual labels:  excel, poi
Easyexcel
快速、简单避免OOM的java处理Excel工具
Stars: ✭ 22,133 (+81874.07%)
Mutual labels:  excel, poi
Excel Boot
Easy-POI是一款Excel导入导出解决方案组成的轻量级开源组件。
Stars: ✭ 347 (+1185.19%)
Mutual labels:  excel, poi
refinery
Refinery is a tool to extract and transform semi-structured data from Excel spreadsheets of different layouts in a declarative way.
Stars: ✭ 30 (+11.11%)
Mutual labels:  excel, poi
Hy.common.report
报表、Excel操作类库。Java转Excel、Excel转Java
Stars: ✭ 124 (+359.26%)
Mutual labels:  excel, poi
poi-mapper
Model to Excel, Excel to Model mapper based on apache poi, java reflection
Stars: ✭ 13 (-51.85%)
Mutual labels:  excel, poi
Poi
☀️ Read and Write Excel file using Java and Apache POI
Stars: ✭ 321 (+1088.89%)
Mutual labels:  excel, poi
Poi Android
📈 Apache POI for Android
Stars: ✭ 77 (+185.19%)
Mutual labels:  excel, poi
Autopoi
AutoPOI 功能如同名字auto,追求的就是自动化,让一个没接触过poi的人员,可以傻瓜化的快速实现Excel导入导出、Word模板导出、可以仅仅5行代码就可以完成Excel的导入导出。
Stars: ✭ 213 (+688.89%)
Mutual labels:  excel, poi
Excel-to-JSON
Excel add-in converting excel to json
Stars: ✭ 15 (-44.44%)
Mutual labels:  excel
json2kml
Python scripts to export Google Maps saved/starred places to KML, CSV, Sygic
Stars: ✭ 42 (+55.56%)
Mutual labels:  poi
swift-declarative-configuration
Declarative configuration for your objects
Stars: ✭ 46 (+70.37%)
Mutual labels:  declarative
json2xls
{"generate excel by json data": "根据json数据生成Excel表格"}
Stars: ✭ 30 (+11.11%)
Mutual labels:  excel

ExcelUtil from Apache POI

Maven Central

ExcelUtil is a Java wrapper using Apache POI to read and write Excel file in declarative fashion.

This library is also introduced as "Related Project" on Apache POI's official website.

Installation

ExcelUtil is using Apache POI version 5.2.2

<dependency>
    <groupId>io.github.nambach</groupId>
    <artifactId>ExcelUtil</artifactId>
    <version>2.5.0</version>
</dependency>

Usage Guides

For full detail guides & example, see the Wiki page.

Quick Guides

Write Excel

Here we have a simple class Book:

class Book {
    private String isbn;
    private String title;
    private double rating;
    private String author;
    private String subCategory;
    private Category category;
    
    static class Category {
        private long id;
        private String name;
    }
}

A very simple usage

The core building block to write data is DataTemplate<T>. It holds mapping rules of the DTO class you need to export Excel.

public class Main {

    static final DataTemplate<Book> BOOK_TEMPLATE = DataTemplate
            .fromClass(Book.class)
            .includeAllFields();

    public static void main(String[] args) {
        InputStream stream = BOOK_TEMPLATE.writeData(books);

        FileUtil.writeToDisk(".../books.xlsx", stream, true);
    }
}

Your DTO class should follow camelCase convention, so that the generated titles would be correct.

Customize Styles

The next building block is Style, which is pretty much the same as what you can configure with normal Excel.

static final Style BASED_STYLE = Style
        .builder()
        .fontName("Calibri")
        .fontSize((short) 12)
        .build();

static final Style HEADER_STYLE = Style
        .builder(BASED_STYLE)     // it is able to accumulate previous style
        .fontColorInHex("#ffffff")
        .backgroundColorInHex("#191970")
        .border(BorderSide.FULL)
        .horizontalAlignment(HorizontalAlignment.LEFT)
        .build();

Since Apache POI has some limitations regarding to stylings, it is recommended to pre-define your styles as static constant for optimization and further reuse.

Below is an example to apply styles conditionally.

public class Main {
    static final Style DATA_STYLE = ...
    static final Style HIGH_RATE = ...
    static final Style FAVORITE_ONE = ...

    static final DataTemplate<Book> BOOK_TEMPLATE = DataTemplate
            .fromClass(Book.class)
            .column(c -> c.field("isbn").title("ISBN"))  // customize column title
            .includeFields("title", "author")
            .column(c -> c.title("Category")
                          .transform(book -> book.getCategory().getName()))  // derive new column
            .column(c -> c.field("rating")
                          .conditionalStyle(book -> book.getRating() > 4 ?  // styles with conditions
                                                    HIGH_RATE : null))
            .config(cf -> cf.startAtCell("A2")
                            .autoSizeColumns(true)
                            .headerStyle(HEADER_STYLE)
                            .dataStyle(DATA_STYLE)
                            .conditionalRowStyle(book -> book.getTitle() // selective styling
                                            .contains("Harry Potter") ? FAVORITE_ONE : null));

    public static void main(String[] args) {
        InputStream stream = BOOK_TEMPLATE.writeData(books);

        FileUtil.writeToDisk(".../books.xlsx", stream, true);
    }
}

Result

Result

Merge rows

You can merge your data rows, either based on same cell values or a particular value that you specify.

Before doing so, you might want to sort your data so that the merging process can perform correctly.

books.sort(Comparator
     .comparing((Book book) -> book.getCategory().getId())
     .thenComparing(comparing(Book::getSubCategory).reversed())
     .thenComparing(Book::getTitle));

Here is example of how to configure merge rows.

static final Style VCENTER = Style.builder().verticalAlignment(VerticalAlignment.CENTER).build();

static final DataTemplate<Book> BOOK_TEMPLATE = DataTemplate
        .fromClass(Book.class)
        .includeFields("title")
        .column(c -> c.field("subCategory")
                      .style(VCENTER)
                      .mergeOnValue(true))  // merge cells with the same value consecutively
        .column(c -> c.title("Category")
                      .style(VCENTER)
                      .transform(book -> book.getCategory().getName())
                      .mergeOnId(book -> book.getCategory().getId()))  // merge on derived value
        .config(cf -> cf.startAtCell("A2")
                        .autoSizeColumns(true));

Result

Result

Read Excel

The building block to read data is ReaderConfig<T>.

ReaderConfig<Book> BOOK_READER = ReaderConfig
        .fromClass(Book.class)
        .titleAtRow(0)
        .dataFromRow(1)
        .column(0, "ibsn")
        .column(1, "title")
        .column(2, "author")
        .column(3, "category");

You can directly retrieve the config from your already defined DataTemplate<T>.

ReaderConfig<Book> BOOK_READER = BOOK_TEMPLATE.getReaderConfig();

InputStream stream = FileUtil.readFromDisk(".../book.xlsx");
List<Book> books = BOOK_READER.readSheet(stream);

For more flexible process while reading data, use built-in callback 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.getRatingMap().put(year, rating);
                           }
                       }));

Documentation

Documentation can be found here.

Notes

  • Minimum JDK version: 1.8
  • Support Excel version:
    • 97-2003 (.xls)
    • 2007+ (.xlsx)

License

Released under Apache-2.0 License.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].