承接 rap2hpoutre/fast-excel 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

rap2hpoutre/fast-excel

Composer 安装命令:

composer require rap2hpoutre/fast-excel

包简介

Fast Excel import/export for Laravel

README 文档

README

Version License StyleCI Tests Total Downloads

Fast Excel import/export for Laravel, thanks to Spout. See benchmarks below.

Quick start

Install via composer:

composer require rap2hpoutre/fast-excel

Export a Model to .xlsx file:

use Rap2hpoutre\FastExcel\FastExcel;
use App\User;

// Load users
$users = User::all();

// Export all users
(new FastExcel($users))->export('file.xlsx');

Export

Export a Model, Query or Collection:

$list = collect([
    [ 'id' => 1, 'name' => 'Jane' ],
    [ 'id' => 2, 'name' => 'John' ],
]);

// export() returns the absolute path to the written file
$path = (new FastExcel($list))->export('file.xlsx');

Export xlsx, ods and csv:

$invoices = App\Invoice::orderBy('created_at', 'DESC')->get();
(new FastExcel($invoices))->export('invoices.csv');

Export only some attributes specifying columns names:

(new FastExcel(User::all()))->export('users.csv', function ($user) {
    return [
        'Email' => $user->email,
        'First Name' => $user->firstname,
        'Last Name' => strtoupper($user->lastname),
    ];
});

Download (from a controller method):

return (new FastExcel(User::all()))->download('file.xlsx');

Import

import returns a Collection:

$collection = (new FastExcel)->import('file.xlsx');

Import a csv with specific delimiter, enclosure characters and "gbk" encoding:

$collection = (new FastExcel)->configureCsv(';', '#', 'gbk')->import('file.csv');

Import and insert to database:

$users = (new FastExcel)->import('file.xlsx', function ($line) {
    return User::create([
        'name' => $line['Name'],
        'email' => $line['Email']
    ]);
});

Facades

You may use FastExcel with the optional Facade. Add the following line to config/app.php under the aliases key.

'FastExcel' => Rap2hpoutre\FastExcel\Facades\FastExcel::class,

Using the Facade, you will not have access to the constructor. You may set your export data using the data method.

$list = collect([
    [ 'id' => 1, 'name' => 'Jane' ],
    [ 'id' => 2, 'name' => 'John' ],
]);

FastExcel::data($list)->export('file.xlsx');

Global helper

FastExcel provides a convenient global helper to quickly instantiate the FastExcel class anywhere in a Laravel application.

$collection = fastexcel()->import('file.xlsx');
fastexcel($collection)->export('file.xlsx');

Advanced usage

Export multiple sheets

Export multiple sheets by creating a SheetCollection:

$sheets = new SheetCollection([
    User::all(),
    Project::all()
]);
(new FastExcel($sheets))->export('file.xlsx');

Use index to specify sheet name:

$sheets = new SheetCollection([
    'Users' => User::all(),
    'Second sheet' => Project::all()
]);

Import multiple sheets

Import multiple sheets by using importSheets:

$sheets = (new FastExcel)->importSheets('file.xlsx');

You can also import a specific sheet by its number:

$users = (new FastExcel)->sheet(3)->import('file.xlsx');

Import multiple sheets with sheets names:

$sheets = (new FastExcel)->withSheetsNames()->importSheets('file.xlsx');

Export large collections with chunk

Export rows one by one to avoid memory_limit issues using yield:

function usersGenerator() {
    foreach (User::cursor() as $user) {
        yield $user;
    }
}

// Export consumes only a few MB, even with 10M+ rows.
(new FastExcel(usersGenerator()))->export('test.xlsx');

Import large files (low memory)

import returns a Collection containing every row, so memory grows with the size of the file. On a file larger than your PHP memory_limit, the default import() fails outright with Allowed memory size of N bytes exhausted. To import a large file without running out of memory, pass a callback and return null — each row is then processed but not accumulated, so memory stays flat:

// Memory stays flat regardless of the number of rows.
(new FastExcel)->import('file.xlsx', function ($line) {
    User::create([
        'name'  => $line['Name'],
        'email' => $line['Email'],
    ]);

    return null; // don't keep the row in memory
});

If the callback returns a value (for example the created model), that value is collected and returned to you — handy for small files, but it keeps every row in memory. Return null when you only need the side effect (e.g. inserting rows).

Importing a 730,000-row file (8 columns), measured under a constrained memory_limit:

How you import Peak memory Result
import($file) (returns a Collection) ~440 MB fails once it exceeds memory_limit
import($file, fn ($row) => null) (streaming) ~4 MB always completes

Reading speed is the same either way — it is dominated by the underlying OpenSpout parser, not by how the rows are returned. The difference above is memory, which is what lets very large files finish at all.

If you would rather keep working with the rows than process them inside a callback, importLazy returns a LazyCollection that streams rows one at a time — you get the full Collection API while memory stays flat:

use Illuminate\Support\LazyCollection;

(new FastExcel)->importLazy('file.xlsx')
    ->chunk(1000)
    ->each(function (LazyCollection $chunk) {
        User::insert($chunk->all());
    });

importLazy accepts the same optional callback as import, and honors sheet(), withoutHeaders(), and header de-duplication. Transposing (transpose()) is not supported with lazy import.

Add header and rows style

Add header and rows style with headerStyle and rowsStyle methods.

use OpenSpout\Common\Entity\Style\Style;

$header_style = (new Style())->setFontBold();

$rows_style = (new Style())
    ->setFontSize(15)
    ->setShouldWrapText()
    ->setBackgroundColor("EDEDED");

return (new FastExcel($list))
    ->headerStyle($header_style)
    ->rowsStyle($rows_style)
    ->download('file.xlsx');

You can also style each header column individually with setHeaderColumnStyles (the header-row counterpart of setColumnStyles). Keys are the zero-based column positions:

use OpenSpout\Common\Entity\Style\Color;
use OpenSpout\Common\Entity\Style\Style;

return (new FastExcel($list))
    ->setHeaderColumnStyles([
        0 => (new Style())->setBackgroundColor(Color::YELLOW),
        1 => (new Style())->setFontColor(Color::BLUE),
    ])
    ->download('file.xlsx');

Export values as strings or numbers

By default numbers are written as numbers and strings as strings. Use stringValues() to force every value to a text cell — handy to keep leading zeros or long numeric IDs (e.g. phone numbers) intact:

// 0660123456 stays "0660123456" instead of becoming 660123456
(new FastExcel($users))->stringValues()->export('users.xlsx');

Need finer control? setColumnFormat() overrides the type per column and takes precedence over stringValues():

(new FastExcel($users))
    ->stringValues()                                  // text by default
    ->setColumnFormat([
        'id'    => 'number',                          // keep as number
        'phone' => 'string',                          // keep as text
    ])
    ->export('users.xlsx');

Why?

FastExcel is intended at being Laravel-flavoured Spout: a simple, but elegant wrapper around Spout with the goal of simplifying imports and exports. It could be considered as a faster (and memory friendly) alternative to Laravel Excel, with less features. Use it only for simple tasks.

Benchmarks

Tested on a MacBook Pro 2015 2,7 GHz Intel Core i5 16 Go 1867 MHz DDR3. Testing a XLSX export for 10000 lines, 20 columns with random data, 10 iterations, 2018-04-05. Don't trust benchmarks.

Average memory peak usage Execution time
Laravel Excel 123.56 M 11.56 s
FastExcel 2.09 M 2.76 s

Still, remember that Laravel Excel has many more features.

rap2hpoutre/fast-excel 适用场景与选型建议

rap2hpoutre/fast-excel 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 27.1M 次下载、GitHub Stars 达 2.31k, 最近一次更新时间为 2018 年 04 月 05 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「excel」 「xls」 「xlsx」 「csv」 「laravel」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 rap2hpoutre/fast-excel 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 rap2hpoutre/fast-excel 我们能提供哪些服务?
定制开发 / 二次开发

基于 rap2hpoutre/fast-excel 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 27.1M
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 2330
  • 点击次数: 19
  • 依赖项目数: 58
  • 推荐数: 2

GitHub 信息

  • Stars: 2314
  • Watchers: 25
  • Forks: 268
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2018-04-05