overview

Origin

Java libraries for manipulating MS Office documents are rare, and one of the more famous ones is Apache’s POI library. While this library is incredibly powerful, it can also be challenging to use. Hutool encapsulates some commonly used tools for POI, making it extremely simple for Java to manipulate Excel and other files.

Introduction

Hutool-poi is a encapsulation of Apache POI, so users need to introduce POI library themselves, Hutool does not introduce it by default. So far, Hutool-poi supports:

  • Reading Excel files (xls, xlsx) using ExcelReader
  • Writing Excel files (xls, xlsx) using ExcelWriter

Usage

Introducing POI Dependency

It is recommended to introduce poi-ooxml, which will automatically associate and introduce the poi package and can well support Office2007+ document formats.

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>${poi.version}</version>
</dependency>

If you need to use Sax to read Excel, you need to introduce the following dependency (not necessary for POI-4.x and above):

<dependency>
    <groupId>xerces</groupId>
    <artifactId>xercesImpl</artifactId>
    <version>${xerces.version}</version>
</dependency>

Note: The version of poi-ooxml for hutool-4.x needs to be higher than 3.17 (don’t ask me why 3.8 doesn’t work, because 3.17 > 3.8) The version of poi-ooxml for hutool-5.x needs to be higher than 4.1.2 The version of poi-ooxml for hutool-5.6.x supports versions higher than 5.0.0 The version of xercesImpl needs to be higher than 2.12.0 (not necessary)

After introducing the dependencies, you can use Hutool’s methods to manipulate Office files. Hutool provides the following classes:

  • ExcelUtil: Excel utility class that encapsulates quick methods for reading.
  • ExcelReader: Excel reader that encapsulates reading Excel, can be constructed and used directly.
  • ExcelWriter: Excel generator and writer that encapsulates writing Excel (writing to a stream or file), can be constructed and used directly.

Frequently Asked Questions

Some users may encounter the following error when using the POI module:

You need to add dependency of 'poi-ooxml' to your project, and version >= 4.1.2

This error is usually caused by one of the following reasons:

  1. POI-related jar files are not introduced or the introduced version is too low.
  2. Multiple versions of POI are introduced, causing package conflicts.
  3. Associated dependencies are not introduced. Check the “Cause By” in the stack trace for details.