fazton/excel

Elegant Excel reader/writer facade over PhpSpreadsheet with memory-optimized APIs and rich features.

Installs: 0

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 0

Forks: 0

pkg:composer/fazton/excel

dev-main 2025-10-30 05:44 UTC

This package is not auto-updated.

Last update: 2025-11-28 04:32:59 UTC


README

Packagist Version Downloads PHP Version License

This project provides two powerful modules to work with Excel files:

  • Excel Writer: Create and export spreadsheets with styling, merging, auto-sizing, properties, protections, and HTML to Excel conversion.
  • Excel Reader: Read and process spreadsheets with column mapping, filters, iterators for large volumes, multi-sheet support, and utilities.

For full technical documentation, see the module pages under docs/.

1: Excel Writer (Summary)

Full docs: docs/excel_writer.md

Method Summary
create() Instantiate writer and create an empty workbook
setFileName(string $fileName) Set output file name and format
addSheet(string $name) Add a sheet and set it active
renameSheet(int|string $indexOrName, string $newName) Rename a sheet
setActiveSheet(int|string $indexOrName) Select active sheet
writeData(array $rows, ?string $sheetName = null, bool $includeHeaders = true, array $options = []) Append rows with optional headers and styles
setCell(string $cell, mixed $value, ?array $style = null) Set a single cell
applyStyle(string $range, array $style) Apply styles to range
writeHtml(string $html, ?string $sheetName = null, array $options = []) Convert HTML table to Excel
autoSizeColumns(int $fromIndex = 1, ?int $toIndex = null, ?string $sheetName = null) Auto-size columns by index range
mergeCells(string $range) Merge cells in a range
setAutoFilter(string $range) Enable auto filter on header range
setProperties(array $properties) Set document properties
protectSheet(?string $sheetName = null, ?string $password = null, array $options = []) Protect sheet
protectWorkbook(?string $password = null) Protect workbook
configureWriter(array $options) Performance and export options
save(?string $filePath = null, string $format = 'Xlsx') Save to disk
download(string $fileName, string $format = 'Xlsx') Stream to client
free() Release resources

Link: docs/excel_writer.md

2: Excel Reader (Summary)

Full docs: docs/excel_reader.md

Method Summary
load(string $filePath) Load Excel file from path
setFileName(string $fileName) Set file name for write mode
setActiveSheet(int|string $indexOrName) Select active sheet
setSheet(int|string $indexOrName) Alias for selecting sheet
addSheet(string $name) Add sheet (write mode)
setColumns(array $columns) Limit/map columns to read
skipHeader(bool $skip = true) Skip the header row
startWhen(string $column, mixed $value, string $operator = '=') Start when a condition matches
stopWhen(string $column, mixed $value, string $operator = '=') Stop when a condition matches
excludeEmpty(bool $exclude = true) Exclude empty rows
getData() Return data as array
eachRow(callable $callback) Iterate row-by-row
chunk(int $size, callable $callback) Process in chunks
getSheetNames() Get sheet names
getSheetCount() Get sheet count
unmergeAllCells() Unmerge all merged cells
getRowCount(?string $sheetName = null) Row count
getColumnCount(?string $sheetName = null) Column count
writeData(array $rows, ?string $sheetName = null, bool $includeHeaders = true) Write mode export
save(string $filePath, string $format = 'Xlsx') Save (write mode)
download(string $fileName, string $format = 'Xlsx') Download (write mode)
free() Release resources

Link: docs/excel_reader.md

For detailed method descriptions, parameters, examples, and special cases, please visit the module documentation pages:

1. Package Description

Fazton/Excel is an elegant facade over PhpSpreadsheet that simplifies reading and writing Excel and CSV files with a clear API, optimized memory usage, and features tailored for large datasets. It provides high-level utilities to:

  • Export data with styles, merges, auto-filters, properties, protections, and HTML-to-Excel conversion.
  • Read spreadsheets with column mapping, advanced filters (startsWith, endsWith, contains), type handling, efficient iteration (eachRow, chunk), and multi-sheet support.

2. System Requirements

  • PHP: ^8.0
  • Dependencies: phpoffice/phpspreadsheet: ^1.29 || ^2.0
  • Recommended extensions (depending on formats and features used):
    • ext-zip for efficient xlsx read/write
    • ext-mbstring for robust string handling
    • ext-gd for image operations (if applicable)

3. Installation

Install via Composer:

composer require fazton/excel

Autoload and basic usage (PSR-4):

<?php
require __DIR__ . '/vendor/autoload.php';

use Fazton\Excel;

// Writer
$writer = Excel::create()
    ->setFileName('report.xlsx')
    ->writeData([
        ['ID', 'Product', 'Price'],
        [1, 'Keyboard', 24.90],
        [2, 'Mouse', 18.50],
    ])
    ->save();

// Reader
$reader = Excel::load(__DIR__ . '/report.xlsx');
$data = $reader->getData();

4. Basic Usage

Writer (create and save):

use Fazton\Excel;

Excel::create()
    ->setFileName('storage/reports.xlsx')
    ->writeData([
        ['Date', 'Sales'],
        ['2024-10-01', 1200],
        ['2024-10-02', 980],
    ])
    ->save();

Reader (load and get data as array):

use Fazton\Excel;

$data = Excel::load('storage/reports.xlsx')
    ->getData();

// Example access
foreach ($data as $row) {
    // $row is an array indexed by column
}

5. Advanced Configuration

  • Writer: performance and export options
Excel::create()
    ->configureWriter([
        'preCalculateFormulas' => false, // speed up exports with formulas
        'useDiskCaching' => true,        // reduce memory footprint
        'diskCachingDir' => sys_get_temp_dir(),
    ])
    ->setFileName('report.xlsx')
    ->writeData($rows)
    ->save();
  • Reader: column mapping and special filters
$reader = Excel::load('report.xlsx')
    ->setColumns([
        // name => original index/key
        'date' => 'A',
        'sales' => 'B',
    ])
    ->excludeEmpty(true)
    ->startWhen('A', '2024', 'startsWith')
    ->stopWhen('B', 0, '<=');

$filtered = $reader->getData();
  • Large file reading
Excel::load('big.xlsx')
    ->chunk(500, function(array $rows, int $offset) {
        // Process 500 rows per chunk
        // Persist to DB, enqueue, etc.
    });

6. Practical Examples

This repository includes runnable examples under examples/:

  • examples/01_writer_basic.php: basic export
  • examples/02_reader_basic.php: basic read
  • examples/04_html_to_excel.php: HTML to Excel conversion
  • examples/05_multi_sheets.php: multi-sheet export
  • examples/07_orders_report.php: report with derived columns and styles

Run an example:

php examples/01_writer_basic.php

7. Testing

Run tests via Composer or PHPUnit:

composer test

Or directly:

vendor/bin/phpunit -c phpunit.xml

Unit tests reside in tests/unit/ and cover the Reader, Writer, and the facade.

8. Contributing

  • Read the guidelines at: docs/contributing.md
  • Code standard: PSR-12
  • PR requirements:
    • Include tests covering your changes
    • Maintain compatibility with PHP ^8.0
    • Update documentation if the API changes
    • Use clear commit structure and descriptions

9. Changelog

The release history is available at: CHANGELOG.md.

10. License

This package is distributed under the MIT license. See LICENSE for details.

2.1 Version Compatibility

| Package | PHP | PhpSpreadsheet | | ------------------------ | ------ | -------------- | --- | ----- | | fazton/excel (current) | ^8.0 | ^1.29 | | ^2.0 |

Notes:

  • Follows Semantic Versioning. Minor releases may add methods without breaking changes.
  • PhpSpreadsheet ^2.0 requires PHP 8; ensure your environment matches.