EasyExcel

repository·master·Indexed 12 days ago

https://github.com/alibaba/easyexcel

A high-performance Java library for reading and writing Excel files, optimized for large datasets with minimal memory consumption compared to Apache POI. It features a simplified API, low memory footprint to prevent OutOfMemoryError, and a 'Speed Mode' for faster processing. The library supports Excel 03 and 07 formats and provides specialized tools for web environment uploads and downloads.

Tokens
7.5K
Snippets
17
Records
40
Agent score
96%

What's inside EasyExcel

  1. What is EasyExcel and why use it?

    master

    EasyExcel is a Java toolkit designed for parsing and generating Excel files with extremely low memory consumption. Unlike Apache POI, which can consume significant memory (e.g., 100MB for a 3MB file) because it often performs unzipping and storage in memory, EasyExcel rewrites the parsing logic to be highly memory-efficient.

    Performance Benchmark (v3.0.2+): A machine with only 64MB RAM can read a 75MB Excel file (460,000 rows, 25 columns) in approximately 20 seconds.

  2. EasyExcel Maintenance Status

    master

    EasyExcel is transitioning into a maintenance mode.

    • What this means: The team will ensure basic functionality remains stable and will provide bug fixes, but there will be no new features actively added.
    • Recommendation: Users are encouraged to evaluate and potentially migrate to other products for new feature requirements.
  3. What is EasyExcel and how does it compare to Apache POI?

    master

    EasyExcel is a Java framework designed for high-performance Excel parsing and generation. Unlike Apache POI, which can be very memory-intensive (e.g., using ~100MB of memory for a 3MB Excel file via SAX), EasyExcel re-implements the parsing of Excel 07 files to significantly reduce memory consumption (e.g., reducing usage to just a few MBs).

    Key features:

    • Low Memory Footprint: Designed to prevent OutOfMemoryError even with very large files.
    • High Speed: Supports a 'Speed Mode' (极速模式) for even faster processing, though it uses slightly more memory (~100MB+).
    • Simplified API: Provides a high-level model conversion wrapper for Excel 03 files, making them easier to use than standard POI SAX modes.
  4. Handle large Excel files (>10MB) with memory optimization

    master

    When processing Excel 07+ files, the 'Shared Strings' concept can cause memory usage to balloon to 3-10x the file size. EasyExcel manages this by switching between in-memory storage and file-based storage for shared strings to prevent OutOfMemoryError.

    Default Behavior

    • Shared Strings < 5MB: Stored in memory (occupies ~15-50MB RAM).
    • Shared Strings > 5MB: Stored in temporary files. A default of 20MB of RAM is used to cache these strings to balance speed and memory.
    • Estimated Memory: For a very large file, expect a permanent memory footprint of approximately 30MB.

    Note: Using file-based storage may reduce reading efficiency by 30-50% due to disk I/O.

  5. Version support and upgrade considerations

    master

    Version Support

    • EasyExcel 2+: Works on Java 6 or Java 7.
    • EasyExcel 3+: Works on Java 8 or higher.

    Upgrading from 2.x to 3.x

    Upgrading across major versions is not recommended due to incompatibilities:

    • Interceptors: Custom interceptors used to modify styles may cause issues even if they compile.
    • Exception Handling: During reading, the invoke function may throw exceptions directly without being wrapped in an ExcelAnalysisException.
    • Annotations: Style and other annotations involving boolean or enumerations have changed (new default values added). You may need to update these annotations to resolve compiler errors.
  6. Use CSV reading and writing with BOM support

    master

    Starting from version 3.3.0, EasyExcel provides enhanced CSV support:

    • BOM Support: When writing CSV files, EasyExcel now includes BOM (Byte Order Mark) data by default to prevent encoding issues (garbled text) when opening files in Microsoft Office.
    • Encoding: You can set specific read/write encodings for CSV files.
    • Auto-detection: If parsing via a file stream, EasyExcel will now default to identifying the format as CSV if it cannot determine otherwise, rather than throwing an exception.
  7. Understand the EasyExcel object hierarchy

    master

    EasyExcel uses a hierarchical configuration model where settings applied to a Workbook are inherited by its Sheets.

    • EasyExcel: The entry point class used to initiate all operations.
    • Workbook (ReadWorkbook/WriteWorkbook): Represents the entire Excel file. You should build one per Excel file.
    • Sheet (ReadSheet/WriteSheet): Represents a single page within the Excel file. You must build one for every sheet you wish to process.
    • ReadListener: A callback mechanism triggered after every row is read to process data.
    • WriteHandler: A callback mechanism triggered during various writing stages (e.g., creating cells or tables).

    Configuration Scope Rule: Settings applied via EasyExcel...sheet() are scoped to that specific sheet. Settings applied before the .sheet() method call apply to the entire Workbook.

  8. Read Excel without creating objects

    master
    Starting from version 3.2.0, EasyExcel supports a mode where you can read raw data types without the overhead of mapping them to Java objects (POJOs). This is useful for high-performance or memory-constrained scenarios where you only need the raw cell values.
  9. Implement Excel file download in a Web environment

    master

    To implement Excel downloading in a web application (e.g., using Spring Boot), you need to configure the HttpServletResponse headers to ensure the browser treats the response as a file download.

    Key steps:

    1. Set the ContentType to application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.
    2. Set the character encoding to utf-8.
    3. Set the Content-disposition header to attachment and encode the filename using URLEncoder to prevent Chinese character corruption.
    4. Use EasyExcel.write(response.getOutputStream(), YourDataClass.class).sheet("SheetName").doWrite(data) to stream the file directly to the response output stream.

    Note: EasyExcel will automatically close the OutputStream when the operation finishes.

    Warning: If using Swagger, you may encounter issues with file downloads; it is recommended to test using a direct browser request or Postman.

    @GetMapping("download")
    public void download(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // Prevent Chinese character corruption
        String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        
        // Write data directly to the response output stream
        EasyExcel.write(response.getOutputStream(), DownloadData.class)
                 .sheet("模板")
                 .doWrite(data());
    }
  10. Install codeStyle plugin for Eclipse

    master

    To format code according to project standards in Eclipse, import the provided Eclipse configuration file:

    1. Navigate to Window -> Preferences -> Java -> Code Style -> Formatter.
    2. Click Import.
    3. Select the file style/eclipse/codestyle.xml from the repository.
    4. In the Active profile section, ensure P3C-CodeStyle is selected.
    5. Click Apply to complete the configuration.
    File: style/eclipse/codestyle.xml
  11. Write Excel files with EasyExcel

    master

    To perform a simple write operation:

    1. Create an entity class (e.g., DemoData) representing the data to be written.
    2. Call EasyExcel.write() specifying the file path and the entity class.
    3. Use .sheet("sheetName") to define the sheet and .doWrite(data) to write the data. The file stream will be closed automatically. If you need to write in the older Excel 03 format, pass the excelType parameter.
    @Test
    public void simpleWrite() {
        String fileName=TestFileUtil.getPath()+"write"+System.currentTimeMillis()+".xlsx";
        // Specify the file name, the entity class, the sheet name, and the data to write
        EasyExcel.write(fileName,DemoData.class).sheet("模板").doWrite(data());
    }
  12. Install EasyExcel via Maven

    master

    To use EasyExcel in your Java project, add the following dependency to your pom.xml. Note that version 3+ requires Java 8 or higher.

    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>easyexcel</artifactId>
        <version>3.0.2</version>
    </dependency>