Home > PHP Framework > Laravel > Laravel development: How to import and export Excel files using Laravel Excel?

Laravel development: How to import and export Excel files using Laravel Excel?

王林
Release: 2023-06-15 16:13:31
Original
3281 people have browsed it

Laravel Development: How to import and export Excel files using Laravel Excel?

With the rapid development of the Internet, data processing is becoming more and more important, especially in enterprise data management. Excel files have become one of the essential tools for corporate offices because they can easily store, edit, calculate, and analyze data. Laravel is a widely used PHP framework, and Laravel Excel is an Excel file operation extension package developed for Laravel, which can easily import and export Excel files.

This article will introduce you to the use of Laravel Excel in detail. In this article, we will learn how to install Laravel Excel and import and export Excel files.

1. Install Laravel Excel

Install Laravel Excel through Composer in the terminal

composer require maatwebsite/excel
Copy after login

If you are using a Laravel version less than 5.5, you need to configure/app.php The following two service providers are configured in the file:

MaatwebsiteExcelExcelServiceProvider::class,
Copy after login
'Excel' => MaatwebsiteExcelFacadesExcel::class,
Copy after login

If you are using a Laravel version greater than or equal to 5.5, you do not need to manually add service providers, these service providers will be automatically added to the configuration.

Publish through the Artisan command in the terminal:

php artisan vendor:publish --provider="MaatwebsiteExcelExcelServiceProvider"
Copy after login

This will automatically generate the following configuration files and template files:

config/excel.php
resources/views/vendor/excel
Copy after login

2. Configure Laravel Excel

The configuration file excel.php contains all configuration options for Laravel Excel. These options can be defined directly in the .env file or configured in the config/excel.php file. Below is a detailed description of all possible options.

'default_driver' => 'local',
Copy after login

The option "default_driver" specifies the default driver to be used. There are two options here: local and ftp.

'cache' => [
    'enabled' => true,
    'driver' => 'laravel',
],
Copy after login

The option "cache" specifies caching options. Caching can improve speed, especially when processing large amounts of data. When caching is enabled, set "cache_driver" to "laravel" or "memcached".

'temp_path' => sys_get_temp_dir(),
Copy after login

Options temp_path specifies the file system path to be used to save temporary files.

'csv' => [
    'delimiter' => ',',
    'enclosure' => '"',
    'escape_character' => '\',
    'input_encoding' => 'UTF-8',
    'output_encoding' => 'UTF-8',
    'use_bom' => false,
],
Copy after login

The option "csv" allows configuring CSV import and export options, which mainly include the following options:

delimiter: delimiter, such as: comma, semicolon, Tab, etc.

enclosure: The enclosure symbol of the column.

escape_character: escape character.

input_encoding: Input encoding.

output_encoding: Output encoding.

use_bom: Whether to use Bom byte order.

'exports' => [
    'force_resave' => false,
    'ignore_empty' => false,
    'pre_calculate_formulas' => false,
    'maximum_recursion' => 50,
],
Copy after login

The option "exports" allows configuring export options, mainly including the following options:

force_resave: whether to force saving.

ignore_empty: Whether to ignore empty cells.

pre_calculate_formulas: Whether to pre-calculate formulas.

maximum_recursion: The maximum number of levels of recursion.

3. Export Excel files

Laravel Excel provides good support for exporting Excel files. Next we will demonstrate how to use Laravel Excel for data export.

First, open the controller file, create a new Excel file and export the data:

<?php

namespace AppHttpControllers;

use MaatwebsiteExcelFacadesExcel;
use AppExportsUsersExport;

class ExportController extends Controller
{
    public function export()
    {
        return Excel::download(new UsersExport, 'users.xlsx');
    }
}
Copy after login

In the above controller method, we use the Excel::download() method to create a Excel file. This method accepts two parameters:

  • The first parameter users will be the exported data. We implement data export by creating a UsersExport auxiliary class with a toExcel() method.
  • The second parameter is the file name, which is required.

The contents of the UsersExport file are as follows:

<?php

namespace AppExports;

use MaatwebsiteExcelConcernsFromCollection;
use AppUser;

class UsersExport implements FromCollection
{
    public function collection()
    {
        return User::select('id', 'name', 'email')->get();
    }
}
Copy after login

This class needs to implement the MaatwebsiteExcelConcernsFromCollection interface. We can see that FromCollection returns a collection class, where the get() method will return all users stored in the class.

In this way, we have completed the export operation of Laravel Excel.

4. Import Excel files

Laravel Excel also provides very good support for the import operation of Excel files. Next we will demonstrate how to use Laravel Excel to import data from Excel files.

First, open the controller file and import the data in the Excel file into the database:

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use AppImportsUsersImport;

class ImportController extends Controller
{
    public function import(Request $request)
    {
        $file = $request->file('file');
        Excel::import(new UsersImport, $file);
        return redirect('/')->with('success', 'Excel 数据已成功导入!');
    }
}
Copy after login

In the above controller method, we use the Excel::import() method to import the Excel file. This method accepts two parameters:

  • The first parameter is UsersImport, which is a class that imports Excel files into the database.
  • The second parameter is the Excel file to be imported, which contains the data to be imported.

Now, let's take a look at the UsersImport class:

<?php

namespace AppImports;

use MaatwebsiteExcelConcernsToModel;
use AppUser;

class UsersImport implements ToModel
{
    public function model(array $row)
    {
        return new User([
            'name' => $row[0],
            'email' => $row[1],
            'password' => bcrypt($row[2])
        ]);
    }
}
Copy after login

As you can see, this class needs to implement the MaatwebsiteExcelConcernsToModel interface, which defines a model() method. This method will be used to determine the attributes of the new user.

In the model() method, we use the data row information of the array to store the user's attributes. Here we assume that the first line in the Excel file is the username, the second line is the email address, and the third line is the password.

This is how we use Laravel Excel to import and export Excel files. I believe you have learned about the basic usage and some advanced features of Laravel Excel. Hope this article is helpful to your Laravel learning.

The above is the detailed content of Laravel development: How to import and export Excel files using Laravel Excel?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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