puddings/quick-excel

Laravel的快速Excel导入/导出

dev-master 2022-04-08 08:14 UTC

This package is not auto-updated.

Last update: 2024-10-03 00:58:35 UTC


README

通过composer安装

composer require Pudding/fast-excel

将模型导出为.xlsx文件

use Pudding\FastExcel\FastExcel;
use App\User;

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

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

导出

导出模型或集合

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

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

导出xlsxodscsv

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

指定列名只导出一些属性

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

下载(从控制器方法中)

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

导入

import返回一个集合

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

导入使用特定分隔符、封装字符和“gbk”编码的csv

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

导入并插入到数据库中

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

外观

您可以使用可选的外观使用FastExcel。将以下行添加到`config/app.php下的aliases键。

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

使用外观,您将无法访问构造函数。您可以使用`data方法设置您的导出数据。

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

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

全局助手

FastExcel提供了一个方便的全局助手,可以在Laravel应用程序的任何位置快速实例化FastExcel类。

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

高级使用

导出多个工作表

通过创建SheetCollection来导出多个工作表

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

使用索引指定工作表名称

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

导入多个工作表

使用importSheets导入多个工作表

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

您还可以通过编号导入特定的工作表

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

使用分块导出大型集合

逐行导出以避免memory_limit问题 使用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');

添加标题和行样式

使用headerStylerowsStyle方法添加标题和行样式。

$header_style = (new StyleBuilder())->setFontBold()->build();

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

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