Class ExcelWriter<T>

java.lang.Object
io.github.dornol.excelkit.excel.ExcelWriter<T>
Type Parameters:
T - The data type of each row to be written into the Excel file

public class ExcelWriter<T> extends Object
ExcelWriter is a utility class for generating large Excel files using Apache POI's SXSSFWorkbook. Supports streaming writes, column configuration, style customization, and sheet auto-splitting.
Since:
2025-07-19
  • Method Details

    • create

      public static <T> ExcelWriter<T> create()
      Creates a new ExcelWriter with default initialization (white header, 1,000,000 max rows, 1000 row window).
      Type Parameters:
      T - the row data type
      Returns:
      a new ExcelWriter instance
    • create

      public static <T> ExcelWriter<T> create(Consumer<ExcelWriter.InitOptions> configurer)
      Creates a new ExcelWriter with initialization options.

      The ExcelWriter.InitOptions passed to the configurer contains settings that must be fixed at workbook creation time — currently only rowAccessWindowSize (SXSSF's in-memory row window, which cannot be changed after the workbook exists). All other configuration (header color, max rows, columns, filters, callbacks, etc.) is set via fluent methods on the returned writer.

      
       ExcelWriter<User> writer = ExcelWriter.<User>create(opts -> opts
           .rowAccessWindowSize(500));
       
      Type Parameters:
      T - the row data type
      Parameters:
      configurer - consumer that configures ExcelWriter.InitOptions
      Returns:
      a new ExcelWriter instance
    • forMap

      public static ExcelWriter<Map<String,Object>> forMap(String... columnNames)
      Creates an ExcelWriter pre-configured to write rows of Map<String, Object>, with one column per given column name. Each column reads its value from the map by using the column name as the key.

      Use this when your data is already in map form and you don't need per-column customization beyond the header labels. The returned writer is a regular ExcelWriter, so all of its fluent configuration methods (row height, auto filter, freeze pane, sheet name, password, etc.) are available.

      
       ExcelWriter.forMap("Name", "Age", "Email")
           .rowHeight(22)
           .autoFilter(true)
           .write(stream)
           .write(out);
       
      Parameters:
      columnNames - the column names (used as both header labels and map keys)
      Returns:
      a new ExcelWriter with the columns registered
      Since:
      0.11.0
    • forMap

      public static ExcelWriter<Map<String,Object>> forMap(Consumer<ExcelWriter.InitOptions> configurer, String... columnNames)
      Creates a map-valued ExcelWriter with initialization options (currently only rowAccessWindowSize). Header color and max rows are set via fluent methods on the returned writer.
      
       ExcelWriter.forMap(
               opts -> opts.rowAccessWindowSize(500),
               "Name", "Age", "City")
           .headerColor(ExcelColor.STEEL_BLUE)
           .maxRows(500_000)
           .autoFilter(true)
           .write(stream)
           .write(out);
       
      Parameters:
      configurer - consumer that configures ExcelWriter.InitOptions
      columnNames - the column names (used as both header labels and map keys)
      Returns:
      a new ExcelWriter with the columns registered
      Since:
      0.13.0
    • forMap

      @SafeVarargs public static ExcelWriter<Map<String,Object>> forMap(String[] columnNames, Consumer<ExcelColumn.ExcelColumnBuilder<Map<String,Object>>>... configurers)
      Creates an ExcelWriter pre-configured for Map<String, Object> rows, with per-column configurers that can adjust type, format, styling, etc.

      Each configurer applies to the column at the matching index. Extra column names beyond the configurers array get no configurer (plain column).

      
       ExcelWriter.forMap(
               new String[]{"Name", "Price", "Date"},
               cfg -> cfg.bold(true),
               cfg -> cfg.type(ExcelDataType.INTEGER),
               cfg -> cfg.type(ExcelDataType.DATE))
           .write(stream)
           .write(out);
       
      Parameters:
      columnNames - the column names
      configurers - per-column configurers (length must not exceed columnNames.length)
      Returns:
      a new ExcelWriter with the columns registered
      Throws:
      IllegalArgumentException - if configurers.length > columnNames.length
      Since:
      0.11.0
    • headerColor

      public ExcelWriter<T> headerColor(ExcelColor color)
      Sets the header background color. Must be called before write(Stream).

      Use presets like ExcelColor.STEEL_BLUE or custom via ExcelColor.of(int, int, int). Defaults to ExcelColor.WHITE.

      Parameters:
      color - header color (must not be null)
      Returns:
      Current ExcelWriter instance for chaining
      Since:
      0.17.0
    • maxRows

      public ExcelWriter<T> maxRows(int maxRows)
      Sets the maximum number of rows per sheet before a new sheet is created. Must be called before write(Stream). Defaults to 1,000,000.
      Parameters:
      maxRows - maximum rows per sheet (must be positive)
      Returns:
      Current ExcelWriter instance for chaining
      Since:
      0.17.0
    • rowHeight

      public ExcelWriter<T> rowHeight(float rowHeightInPoints)
      Sets the row height for data rows in points. Defaults to 20 points.
      Parameters:
      rowHeightInPoints - Row height in points (must be positive)
      Returns:
      Current ExcelWriter instance for chaining
    • autoFilter

      public ExcelWriter<T> autoFilter(boolean autoFilter)
      Enables or disables auto-filter on the header row.
      Parameters:
      autoFilter - Whether to apply auto-filter
      Returns:
      Current ExcelWriter instance for chaining
    • freezeRows

      public ExcelWriter<T> freezeRows(int rows)
      Freezes the given number of rows below the header row.

      For both-axes freezing use freezePane(int, int); for columns-only use freezeCols(int).

      Parameters:
      rows - Number of rows to freeze (must be non-negative)
      Returns:
      Current ExcelWriter instance for chaining
      Since:
      0.16.6
    • freezeCols

      public ExcelWriter<T> freezeCols(int cols)
      Freezes the given number of columns from the left edge.

      For both-axes freezing use freezePane(int, int); for rows-only use freezeRows(int).

      Parameters:
      cols - Number of columns to freeze (must be non-negative)
      Returns:
      Current ExcelWriter instance for chaining
      Since:
      0.16.6
    • freezePane

      public ExcelWriter<T> freezePane(int cols, int rows)
      Sets the number of columns and rows to freeze.

      Columns are frozen from the left edge, rows are frozen below the header row. This is useful for data entry forms and ledgers where both ID columns and header rows should remain visible while scrolling.

      Parameters:
      cols - Number of columns to freeze from the left (must be non-negative)
      rows - Number of rows to freeze below the header (must be non-negative)
      Returns:
      Current ExcelWriter instance for chaining
    • beforeHeader

      public ExcelWriter<T> beforeHeader(BeforeHeaderWriter beforeHeaderWriter)
      Registers a callback that writes custom content before the column header row.

      The callback is invoked on every sheet, including rollover sheets, so it must always produce the same number of rows.

      Parameters:
      beforeHeaderWriter - the callback to invoke before writing column headers
      Returns:
      Current ExcelWriter instance for chaining
    • afterData

      public ExcelWriter<T> afterData(AfterDataWriter afterDataWriter)
      Registers a callback that writes custom content after all data rows on each sheet.

      Called on every sheet (including rollover sheets) after its data rows are written. On the last sheet, this is called before afterAll.

      Parameters:
      afterDataWriter - the callback to invoke after data rows
      Returns:
      Current ExcelWriter instance for chaining
    • afterAll

      public ExcelWriter<T> afterAll(AfterDataWriter afterAllWriter)
      Registers a callback that writes custom content once on the last sheet after all data.

      Called only once, on the last sheet, after afterData (if set). Useful for writing grand totals or summary rows.

      Parameters:
      afterAllWriter - the callback to invoke after all data is written
      Returns:
      Current ExcelWriter instance for chaining
    • sheetName

      public ExcelWriter<T> sheetName(Function<Integer,String> sheetNameFunction)
      Sets a function that generates sheet names based on the sheet index (0-based).
      Parameters:
      sheetNameFunction - a function that takes the sheet index and returns the sheet name
      Returns:
      Current ExcelWriter instance for chaining
    • sheetName

      public ExcelWriter<T> sheetName(String name)
      Sets a fixed sheet name. When sheets roll over, subsequent sheets are named "{name} (2)", "{name} (3)", etc.
      Parameters:
      name - the base sheet name
      Returns:
      Current ExcelWriter instance for chaining
    • rowColor

      public ExcelWriter<T> rowColor(Function<T,@Nullable ExcelColor> rowColorFunction)
      Sets a function that determines the background color for each row.

      When set, the function is called for each row of data. If it returns a non-null ExcelColor, that color is applied as the background to all cells in the row, overriding any column-level background color.

      Parameters:
      rowColorFunction - function that takes row data and returns an ExcelColor (or null for no override)
      Returns:
      Current ExcelWriter instance for chaining
    • onProgress

      public ExcelWriter<T> onProgress(int interval, ProgressCallback callback)
      Registers a progress callback that fires every interval rows.
      Parameters:
      interval - the number of rows between each callback invocation (must be positive)
      callback - the callback to invoke
      Returns:
      Current ExcelWriter instance for chaining
    • autoWidthSampleRows

      public ExcelWriter<T> autoWidthSampleRows(int rows)
      Sets the number of rows sampled for auto column width calculation.

      Only the first N data rows are measured to determine column widths. Set to 0 to disable auto-width (all columns use minimum width). Defaults to 100.

      Parameters:
      rows - number of rows to sample (0 to disable)
      Returns:
      Current ExcelWriter instance for chaining
    • protectSheet

      public ExcelWriter<T> protectSheet(String password)
      Protects all sheets with the given password.

      When sheet protection is enabled, cells are locked by default. Use ColumnStyleConfig.locked(boolean) to allow editing specific columns.

      Parameters:
      password - the protection password
      Returns:
      Current ExcelWriter instance for chaining
    • conditionalFormatting

      public ExcelWriter<T> conditionalFormatting(Consumer<ExcelConditionalRule> configurer)
      Adds a conditional formatting rule.
      Parameters:
      configurer - consumer to configure the rule
      Returns:
      Current ExcelWriter instance for chaining
    • chart

      public ExcelWriter<T> chart(Consumer<ExcelChartConfig> configurer)
      Configures a chart to be added after all data is written.
      Parameters:
      configurer - consumer to configure the chart
      Returns:
      Current ExcelWriter instance for chaining
    • printSetup

      public ExcelWriter<T> printSetup(Consumer<ExcelPrintSetup> configurer)
      Configures print setup (page layout) for all sheets.

      Controls orientation, paper size, margins, headers/footers, repeat rows, and fit-to-page.

      Parameters:
      configurer - consumer to configure the print setup
      Returns:
      Current ExcelWriter instance for chaining
    • tabColor

      public ExcelWriter<T> tabColor(int r, int g, int b)
      Sets the sheet tab color using RGB values.
      Parameters:
      r - Red component (0–255)
      g - Green component (0–255)
      b - Blue component (0–255)
      Returns:
      Current ExcelWriter instance for chaining
      Since:
      0.7.0
    • tabColor

      public ExcelWriter<T> tabColor(ExcelColor color)
      Sets the sheet tab color using a preset color.
      Parameters:
      color - Preset color
      Returns:
      Current ExcelWriter instance for chaining
      Since:
      0.7.0
    • protectWorkbook

      public ExcelWriter<T> protectWorkbook(String password)
      Protects the workbook structure with the given password.

      When enabled, users cannot add, delete, rename, or reorder sheets.

      Parameters:
      password - the protection password
      Returns:
      Current ExcelWriter instance for chaining
    • password

      public ExcelWriter<T> password(String password)
      Sets the file encryption password.

      When set, the resulting Excel file will be encrypted using the "agile" encryption mode, and ExcelHandler.writeTo(java.io.OutputStream) will automatically apply encryption — no need to pass the password to ExcelHandler.writeTo(java.io.OutputStream, String).

      Parameters:
      password - the encryption password (must not be null or blank)
      Returns:
      Current ExcelWriter instance for chaining
    • headerFontName

      public ExcelWriter<T> headerFontName(String fontName)
      Sets the header font name.
      Parameters:
      fontName - the font name (e.g., "Arial", "맑은 고딕")
      Returns:
      Current ExcelWriter instance for chaining
    • headerFontSize

      public ExcelWriter<T> headerFontSize(int fontSize)
      Sets the header font size in points.
      Parameters:
      fontSize - font size in points (must be positive)
      Returns:
      Current ExcelWriter instance for chaining
    • defaultStyle

      public ExcelWriter<T> defaultStyle(Consumer<ColumnStyleConfig.DefaultStyleConfig<T>> configurer)
      Sets default column styles that apply to all columns unless overridden per-column.
      Parameters:
      configurer - consumer to configure default style properties
      Returns:
      Current ExcelWriter instance for chaining
    • summary

      public ExcelWriter<T> summary(Consumer<ExcelSummary> configurer)
      Configures summary (footer) rows with formulas such as SUM, AVERAGE, COUNT, MIN, MAX.

      Summary rows are appended after data rows on each sheet.

      Parameters:
      configurer - consumer to configure the summary
      Returns:
      Current ExcelWriter instance for chaining
    • column

      public ExcelWriter<T> column(String name, Function<T,@Nullable Object> function)
      Adds a column with default STRING type using a simple Function. Useful for schema-based column registration.
      Parameters:
      name - Column header name
      function - Function to extract cell value from row
      Returns:
      Current ExcelWriter instance for chaining
    • column

      public ExcelWriter<T> column(String name, Function<T,@Nullable Object> function, Consumer<ExcelColumn.ExcelColumnBuilder<T>> configurer)
      Adds a column with additional configuration using a configurer consumer.

      The configurer receives an ExcelColumn.ExcelColumnBuilder to set column properties such as type, format, alignment, width, etc.

      
       writer.column("Price", Book::getPrice, c -> c.type(ExcelDataType.INTEGER).format("#,##0"));
       
      Parameters:
      name - Column header name
      function - Function to extract cell value from row
      configurer - Consumer to configure column properties
      Returns:
      Current ExcelWriter instance for chaining
    • column

      public ExcelWriter<T> column(String name, RowFunction<T,@Nullable Object> function)
      Adds a column with cursor access using an RowFunction. Useful when the column value depends on row position (e.g., row number).
      Parameters:
      name - Column header name
      function - Function to extract cell value from row with cursor access
      Returns:
      Current ExcelWriter instance for chaining
    • column

      public ExcelWriter<T> column(String name, RowFunction<T,@Nullable Object> function, Consumer<ExcelColumn.ExcelColumnBuilder<T>> configurer)
      Adds a column with cursor access and additional configuration.
      Parameters:
      name - Column header name
      function - Function to extract cell value from row with cursor access
      configurer - Consumer to configure column properties
      Returns:
      Current ExcelWriter instance for chaining
    • columnIf

      public ExcelWriter<T> columnIf(String name, boolean condition, Function<T,@Nullable Object> function)
      Conditionally adds a column with default STRING type using a simple Function. If condition is false, the column is not added.
      Parameters:
      name - Column header name
      condition - Whether to include this column
      function - Function to extract cell value from row
      Returns:
      Current ExcelWriter instance for chaining
    • columnIf

      public ExcelWriter<T> columnIf(String name, boolean condition, Function<T,@Nullable Object> function, Consumer<ExcelColumn.ExcelColumnBuilder<T>> configurer)
      Conditionally adds a column with additional configuration. If condition is false, the column is not added.
      Parameters:
      name - Column header name
      condition - Whether to include this column
      function - Function to extract cell value from row
      configurer - Consumer to configure column properties
      Returns:
      Current ExcelWriter instance for chaining
    • columnIf

      public ExcelWriter<T> columnIf(String name, boolean condition, RowFunction<T,@Nullable Object> function)
      Conditionally adds a column with cursor access using an RowFunction. If condition is false, the column is not added.
      Parameters:
      name - Column header name
      condition - Whether to include this column
      function - Function to extract cell value from row with cursor access
      Returns:
      Current ExcelWriter instance for chaining
    • columnIf

      public ExcelWriter<T> columnIf(String name, boolean condition, RowFunction<T,@Nullable Object> function, Consumer<ExcelColumn.ExcelColumnBuilder<T>> configurer)
      Conditionally adds a column with cursor access and additional configuration. If condition is false, the column is not added.
      Parameters:
      name - Column header name
      condition - Whether to include this column
      function - Function to extract cell value from row with cursor access
      configurer - Consumer to configure column properties
      Returns:
      Current ExcelWriter instance for chaining
    • constColumn

      public ExcelWriter<T> constColumn(String name, @Nullable Object value)
      Adds a column with a constant value for all rows.
      Parameters:
      name - Column header name
      value - Constant value to be used in all rows
      Returns:
      Current ExcelWriter instance for chaining
    • constColumn

      public ExcelWriter<T> constColumn(String name, @Nullable Object value, Consumer<ExcelColumn.ExcelColumnBuilder<T>> configurer)
      Adds a column with a constant value for all rows, with additional configuration.
      Parameters:
      name - Column header name
      value - Constant value to be used in all rows
      configurer - Consumer to configure column properties
      Returns:
      Current ExcelWriter instance for chaining
    • constColumnIf

      public ExcelWriter<T> constColumnIf(String name, boolean condition, @Nullable Object value)
      Conditionally adds a column with a constant value for all rows. If condition is false, the column is not added.
      Parameters:
      name - Column header name
      condition - Whether to include this column
      value - Constant value to be used in all rows
      Returns:
      Current ExcelWriter instance for chaining
    • write

      public ExcelHandler write(Stream<T> stream, WriteRowCallback<T> consumer)
      Writes the stream of row data into an Excel file using custom row-level callback.
      Parameters:
      stream - The data stream
      consumer - Custom consumer for post-processing row with cursor
      Returns:
      ExcelHandler wrapping the workbook
    • write

      public ExcelHandler write(Stream<T> stream)
      Writes the stream of row data into Excel file without row-level callback.
      Parameters:
      stream - The data stream
      Returns:
      ExcelHandler wrapping the workbook