Home > PHP Framework > Laravel > body text

Let's talk about five little-known functions of Laravel Excel

青灯夜游
Release: 2023-01-12 21:03:19
forward
1800 people have browsed it

Let's talk about five little-known functions of Laravel Excel

Laravel Excel package Recently released version 3.0, it has new features that can help simplify advanced needs and is extremely usable. Let’s explore some of the hidden features you may not know that make Laravel Excel the best choice for Excel extensions.

1. Import data from HTML or Blade

Assume there is already an HTML table

Lets talk about five little-known functions of Laravel Excel

Template code -- 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>
Copy after login

You can use it to repeatedly import this table into Excel

Step 1. Generate an Export class

php artisan make:export CustomersFromView --model=Customer
Copy after login

Step 2. Use FromView to operate

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(&#39;customers.table&#39;, [
            &#39;customers&#39; => Customer::orderBy(&#39;id&#39;, &#39;desc&#39;)->take(100)->get()
        ]);
    }
}
Copy after login

Here is the imported Excel Lets talk about five little-known functions of Laravel Excel:

Lets talk about five little-known functions of Laravel Excel

Note: Only HTML tables can be exported here and cannot have any Tags, such as html, body, div, etc.


2. Export to PDF, HTML, or other format Lets talk about five little-known functions of Laravel Excels

Although the name of the package is Laravel Excel, it provides a variety of export formats and is very simple to use. , just add another parameter to the class:

return Excel::download(new CustomersExport(), &#39;customers.xlsx&#39;, &#39;Html&#39;);
Copy after login

For example, if you do this, it will be exported to HTML, as shown below:

Lets talk about five little-known functions of Laravel Excel

Not too There are many styles, here is the source code:

Lets talk about five little-known functions of Laravel Excel

Not only that, it can also be exported to PDF, and you can even choose three libraries from it. The usage method is the same, you Just specify the format in the last parameter. Here are some examples. Document Example:

Lets talk about five little-known functions of Laravel Excel

Note: You must install the specified PDF package through composer, for example:

composer require dompdf/dompdf
Copy after login

The exported PDF is as follows Display:

Lets talk about five little-known functions of Laravel Excel


3. Format cells as needed

Laravel Excel has a powerful "dad" -- PhpSpreadsheet . So it has its various underlying functions, including various ways of cell formatting.

Here is an example of how to use it in a Laravel Export class, such as app/Exports/CustomersExportStyling.php:

Step 1. Introduce the appropriate class in the header.

use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Events\AfterSheet;
Copy after login

Step 2. Use the WithEvents interface in the implements section.

class CustomersExportStyling implements FromCollection, WithEvents
{
    // ...
Copy after login

Step 3. Use the AfterSheet event to create the registerEvents() method.

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

Here is an example:

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

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

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

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

The results displayed by these "random" samples are as follows:

Lets talk about five little-known functions of Laravel Excel

You can Find all of the above and many more examples in the Recipes page of PhpSpreadsheet docs.


4. Hidden model attributes

Assume we have created the Laravel 5.7default users table:

Lets talk about five little-known functions of Laravel Excel

Now we try to use a simple FromCollection to export user table data:

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

In the exported Excel, you can only see the following fields, but There is no password and remember_token:

Lets talk about five little-known functions of Laravel Excel

This is because hidden fields are defined in the User model Attributes:

class User extends Authenticatable
{
    // ...

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

So, these fields are hidden by default. If you want some fields not to be exported when exporting data, you can directly define hidden attributes in the model$hidden.


5. Formulas

For some reason, formulas are not mentioned in the official documentation of the Laravel Excel package, but this is an important function of Excel!

Fortunately, we can write the formula directly in the class that exports the data. We need to set the value of cell, like this: =A2 1 or SUM(A1 :A10).

One of the ways is to implement the WithMapping interface:

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,
            &#39;=A2+1&#39;,
            $customer->first_name,
            $customer->last_name,
            $customer->email,
        ];
    }
}
Copy after login

The above are the five little-known functions of Laravel Excel.

Original address: https://laravel-news.com/five-hidden-features-of-the-laravel-excel-package

Translation address: https:// learnku.com/laravel/t/24161

[Related recommendations: laravel video tutorial]

The above is the detailed content of Let's talk about five little-known functions of Laravel Excel. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:learnku.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template