Skip to content

ExcelWriter with Sheet API

ExcelWriter is a component of the EasyExcel library designed to handle the writing of Excel data programmatically^[600-developer-java-3-party-easyexcel.md]. It utilizes a Sheet API to manage the structure and content of the output spreadsheet.

Core Components

The writing process relies on three primary elements:

  • OutputStream: The destination for the file data (e.g., a FileOutputStream).^[600-developer-java-3-party-easyexcel.md]
  • ExcelWriter: The main object initialized with the output stream and Excel type (e.g., ExcelTypeEnum.XLSX).^[600-developer-java-3-party-easyexcel.md]
  • Sheet: Defines the specific sheet within the workbook, including its index (sheet number) and the class used for model mapping.^[600-developer-java-3-party-easyexcel.md]

Usage Workflow

The typical workflow involves initializing the writer with an output stream, defining one or more sheets, writing data to them, and finalizing the operation.

  1. Initialization: Create an ExcelWriter instance, specifying the output stream and the file format.^[600-developer-java-3-party-easyexcel.md]
  2. Sheet Configuration: Instantiate a Sheet object. This object defines the sheet number and the data model class (e.g., ExcelPropertyIndexModel.class) that maps fields to columns.^[600-developer-java-3-party-easyexcel.md]
  3. Writing Data: Pass the data collection and the configured Sheet object to the writer.write() method.^[600-developer-java-3-party-easyexcel.md]
  4. Finalization: Always call writer.finish() to ensure resources are released and the file is correctly formatted.^[600-developer-java-3-party-easyexcel.md]

Example

The following example demonstrates writing a list of data to a specific sheet:

OutputStream out = new FileOutputStream("/Users/jipengfei/78.xlsx");
try {
    ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX);
    // Configure the sheet: Sheet No. 1, head line number 0, mapped to a specific model class
    Sheet sheet1 = new Sheet(1, 0, ExcelPropertyIndexModel.class);
    writer.write(getData(), sheet1);
    writer.finish();
} catch (Exception e) {
    e.printStackTrace();
} finally {
    out.close();
}
^[600-developer-java-3-party-easyexcel.md]

  • EasyExcel
  • [[AnalysisEventListener]] (Used for reading with ExcelReader)
  • [[OutputStream]]
  • [[Java Libraries]]

Sources

^[600-developer-java-3-party-easyexcel.md]