fiberphp/excel

📊 FiberPHP Excel 组件 —— 双驱动适配(xlswriter/PhpSpreadsheet),支持大数据分块读写、声明式导入导出。

Maintainers

Package info

gitee.com/fiberphp/excel

pkg:composer/fiberphp/excel

Transparency log

Statistics

Installs: 0

Dependents: 0

Suggesters: 0

dev-master 2026-08-23 06:58 UTC

This package is auto-updated.

Last update: 2026-08-23 06:58:11 UTC


README

双驱动适配(xlswriter/PhpSpreadsheet),支持大数据分块读写、声明式导入导出。

目录结构

src/
├── Excel.php                  # 统一入口
├── Exporter.php               # 导出器
├── Importer.php               # 导入器
├── Install.php                # 安装器(发布配置)
├── helpers.php                # 助手函数 excel()
├── Exception/
│   └── ExcelException.php    # 异常
├── Contract/
│   └── DriverInterface.php    # 驱动契约
└── Driver/
    ├── MemoryDriver.php        # 内存驱动(测试/调试)
    ├── XlswriterDriver.php     # xlswriter 驱动(高性能,默认)
    └── PhpSpreadsheetDriver.php # PhpSpreadsheet 驱动(全格式)
config/
└── excel.php                  # 配置文件
tests/
├── ExcelTest.php              # 10 个测试用例
└── bootstrap.php

安装

composer require fiberphp/excel

驱动安装(按需选一)

# 方案 A:xlswriter C 扩展(高性能,大文件首选)
pecl install xlswriter

# 方案 B:PhpSpreadsheet(纯 PHP,格式更全)
composer require phpoffice/phpspreadsheet

配置

config/excel.php

return [
    'driver' => extension_loaded('xlswriter') ? 'xlswriter' : 'phpspreadsheet',
    'tmp_dir' => runtime_path('excel'),
    'export_format' => 'xlsx',
    'chunk_size' => 1000,
    'xlswriter' => ['memory_threshold' => 100],
    'phpspreadsheet' => ['cache' => 'disk'],
];

快速开始

快捷导出

use FiberPHP\Excel\Excel;

// 数组导出
Excel::export([
    ['id' => 1, 'name' => '张三', 'email' => 'zhang@example.com'],
    ['id' => 2, 'name' => '李四', 'email' => 'li@example.com'],
], ['ID', '姓名', '邮箱'])
    ->store(runtime_path('exports/users.xlsx'));

// 下载
Excel::export($data, $headings)->download('users.xlsx');

快捷导入

// 全量读取
$rows = Excel::import('users.xlsx')->toArray();

// 分块读取(大文件内存优化)
foreach (Excel::import('large.xlsx')->chunk(1000) as $chunk) {
    foreach ($chunk as $row) {
        UserModel::create($row);
    }
}

助手函数

excel()->export($data, $headings)->download('users.xlsx');
excel()->import('users.xlsx')->toArray();

双驱动对比

维度xlswriterPhpSpreadsheet
性能100万行 ~3s100万行 ~60s+
内存~5MB(磁盘模式)~500MB+
格式xlsx, csvxlsx, xls, csv, ods, html
样式基础完整(图表/公式)
依赖C 扩展纯 composer

自定义驱动

use FiberPHP\Excel\Contract\DriverInterface;

class CustomDriver implements DriverInterface
{
    public function write(string $file, array $data, ?array $headings = null): void { ... }
    public function read(string $file, ?int $chunkSize = null): \Generator { ... }
    public function format(): string { return 'xlsx'; }
}

// 注入
Excel::setDriver(new CustomDriver());

API

Excel

方法说明
export($data, $headings)准备导出数据
import($file)准备导入文件
setDriver($driver)注入自定义驱动
driver()获取当前驱动实例

Exporter

方法说明
toArray()导出为数组
toJson()导出为 JSON
toFile($path)写入文件
download($filename)HTTP 下载

Importer

方法说明
toArray()全量读取
chunk($size)分块读取(Generator)

测试

composer install
./vendor/bin/phpunit

License

MIT