Laravel Excel 的五个隐藏功能

栏目: PHP · 发布时间: 7年前

内容简介:假设已经有一个 HTML 表格

Laravel Excel 的五个隐藏功能

Laravel Excel package 最近发布了 3.0 版本,它所具有的新功能,可以帮助简化高级需求,并且可用性极高。大家一起来探讨一下可能不知道的一些隐藏功能,这些功能使 Laravel Excel 成为 Excel 拓展的最佳首选。

1. 从 HTML 或者是 Blade 导入数据

假设已经有一个 HTML 表格

Laravel Excel 的五个隐藏功能

模版代码 -- resources/views/customers/table.blade.php:

<table class="table">
    <thead>
    <tr>
        <th></th>
        <th>First name</th>
        <th>Last name</th>
        <th>Email</th>
        <th>Created at</th>
        <th>Updated at</th>
    </tr>
    </thead>
    <tbody>
    @foreach ($customers as $customer)
    <tr>
        <td>{{ $customer->id }}</td>
        <td>{{ $customer->first_name }}</td>
        <td>{{ $customer->last_name }}</td>
        <td>{{ $customer->email }}</td>
        <td>{{ $customer->created_at }}</td>
        <td>{{ $customer->updated_at }}</td>
    </tr>
    @endforeach
    </tbody>
</table>

你可以使用它去重复导入这个表格到 Excel

步骤1. 生成一个 Export 类

php artisan make:export CustomersFromView --model=Customer

步骤2. 使用 FromView 进行操作

namespace App\Exports;

use App\Customer;
use Illuminate\Contracts\View\View;
use Maatwebsite\Excel\Concerns\FromView;

class CustomersExportView implements FromView
{
    public function view(): View
    {
        return view('customers.table', [
            'customers' => Customer::orderBy('id', 'desc')->take(100)->get()
        ]);
    }
}

这里是导入的 Excel 文件:

Laravel Excel 的五个隐藏功能

注意:这里只能导出 HTML 表格,不能具有任何标签,比如 html,body,div 等。

2. 导出到 PDF,HTML,或是其他格式的文件

虽然包的名称是 Laravel Excel,但是提供了多种导出格式,并且使用起来十分简单,只要在类里再添加一个参数即可:

return Excel::download(new CustomersExport(), 'customers.xlsx', 'Html');

比如这么做,就导出到了HTML,如下图所示:

Laravel Excel 的五个隐藏功能

没有太多的样式,下面是源代码:

Laravel Excel 的五个隐藏功能

不仅如此,它还可以导出到 PDF,甚至你可以从中选择三种库,使用方法是一样的,你只要在最后一个参数指定格式就好了,下面是一些例子。 文档示例 :

Laravel Excel 的五个隐藏功能

注意:你必须通过 composer 安装指定的 PDF 包,比如:

composer require dompdf/dompdf

导出的 PDF 如下所示:

Laravel Excel 的五个隐藏功能

3. 按需格式化单元格

Laravel Excel 有一个强有力的「爸爸」 -- PhpSpreadsheet 。因此它就拥有其各种底层功能,包括各种方式的单元格格式化。

此处是一个如何在 Laravel Export 类中使用它的例子,例如 app/Exports/CustomersExportStyling.php:

步骤 1. 在头部引入适当的类。

use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Events\AfterSheet;

步骤 2. 在 implements 部分使用 WithEvents 接口。

class CustomersExportStyling implements FromCollection, WithEvents
{
    // ...

步骤 3. 用 AfterSheet 事件来创建 registerEvents() 方法。

/**
 * @return array
 */
public function registerEvents(): array
{
    return [
        AfterSheet::class    => function(AfterSheet $event) {
            // ... 此处你可以任意格式化
        },
    ];
}

这里有个例子:

/**
 * @return array
 */
public function registerEvents(): array
{
    return [
        AfterSheet::class    => function(AfterSheet $event) {
            // 所有表头-设置字体为14
            $cellRange = 'A1:W1';
            $event->sheet->getDelegate()->getStyle($cellRange)->getFont()->setSize(14);

            // 将样式数组应用于B2:G8范围单元格
            $styleArray = [
                'borders' => [
                    'outline' => [
                        'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THICK,
                        'color' => ['argb' => 'FFFF0000'],
                    ]
                ]
            ];
            $event->sheet->getDelegate()->getStyle('B2:G8')->applyFromArray($styleArray);

            // 将第一行行高设置为20
            $event->sheet->getDelegate()->getRowDimension(1)->setRowHeight(20);

            // 设置 A1:D4 范围内文本自动换行
            $event->sheet->getDelegate()->getStyle('A1:D4')
                ->getAlignment()->setWrapText(true);
        },
    ];
}

这些「随机」样例展示的结果如下所示:

Laravel Excel 的五个隐藏功能

你可以在 Recipes page of PhpSpreadsheet docs 中找到所有的以上以及更多示例。

4. 隐藏模型属性

假设我们已经创建了 Laravel 5.7 默认的 users 表:

Laravel Excel 的五个隐藏功能

现在我们尝试用简单的 FromCollection 来导出用户表数据:

class UsersExport implements FromCollection
{
    public function collection()
    {
        return User::all();
    }
}

在导出的Excel 里,你只能看到如下字段,但是没有 passwordremember_token

Laravel Excel 的五个隐藏功能

这是因为在 User 模型里定义了隐藏字段的属性:

class User extends Authenticatable
{
    // ...

    /**
     * 这个数组用来定义需要隐藏的字段。
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

所以,默认情况下这些字段是隐藏的,如果你想在导出数据的时候某些字段不被导出的话,可以直接在模型中定义隐藏属性 $hidden

5. 公式

出于某种原因,Laravel Excel 包的官方文档中并没有提及公式,但是这是Excel 重要的功能!

幸运的是,我们可以直接将公式写在导出数据的类中,我们需要设置 cell 的值,就像这样: =A2+1 or SUM(A1:A10)

其中一种方式就是实现 WithMapping 接口:

use App\Customer;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithMapping;

class CustomersExportFormulas implements FromCollection, WithMapping
{
    public function collection()
    {
        return Customer::all();
    }

    /**
     * @var Customer $customer
     * @return array
     */
    public function map($customer): array
    {
        return [
            $customer->id,
            '=A2+1',
            $customer->first_name,
            $customer->last_name,
            $customer->email,
        ];
    }
}

以上就是Laravel Excel的五个鲜为人知的功能。

文章转自: https://learnku.com/laravel/t...

更多文章: https://learnku.com/laravel/c...


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Web Security Testing Cookbook

Web Security Testing Cookbook

Paco Hope、Ben Walther / O'Reilly Media / 2008-10-24 / USD 39.99

Among the tests you perform on web applications, security testing is perhaps the most important, yet it's often the most neglected. The recipes in the Web Security Testing Cookbook demonstrate how dev......一起来看看 《Web Security Testing Cookbook》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

在线进制转换器
在线进制转换器

各进制数互转换器

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码