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?

Jun 15, 2023 pm 04:13 PM
excel laravel Import and Export

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Complete collection of excel function formulas Complete collection of excel function formulas May 07, 2024 pm 12:04 PM

1. The SUM function is used to sum the numbers in a column or a group of cells, for example: =SUM(A1:J10). 2. The AVERAGE function is used to calculate the average of the numbers in a column or a group of cells, for example: =AVERAGE(A1:A10). 3. COUNT function, used to count the number of numbers or text in a column or a group of cells, for example: =COUNT(A1:A10) 4. IF function, used to make logical judgments based on specified conditions and return the corresponding result.

Comparison of the latest versions of Laravel and CodeIgniter Comparison of the latest versions of Laravel and CodeIgniter Jun 05, 2024 pm 05:29 PM

The latest versions of Laravel 9 and CodeIgniter 4 provide updated features and improvements. Laravel9 adopts MVC architecture and provides functions such as database migration, authentication and template engine. CodeIgniter4 uses HMVC architecture to provide routing, ORM and caching. In terms of performance, Laravel9's service provider-based design pattern and CodeIgniter4's lightweight framework give it excellent performance. In practical applications, Laravel9 is suitable for complex projects that require flexibility and powerful functions, while CodeIgniter4 is suitable for rapid development and small applications.

Laravel - Artisan Commands Laravel - Artisan Commands Aug 27, 2024 am 10:51 AM

Laravel - Artisan Commands - Laravel 5.7 comes with new way of treating and testing new commands. It includes a new feature of testing artisan commands and the demonstration is mentioned below ?

How do the data processing capabilities in Laravel and CodeIgniter compare? How do the data processing capabilities in Laravel and CodeIgniter compare? Jun 01, 2024 pm 01:34 PM

Compare the data processing capabilities of Laravel and CodeIgniter: ORM: Laravel uses EloquentORM, which provides class-object relational mapping, while CodeIgniter uses ActiveRecord to represent the database model as a subclass of PHP classes. Query builder: Laravel has a flexible chained query API, while CodeIgniter’s query builder is simpler and array-based. Data validation: Laravel provides a Validator class that supports custom validation rules, while CodeIgniter has less built-in validation functions and requires manual coding of custom rules. Practical case: User registration example shows Lar

Laravel vs CodeIgniter: Which framework is better for large projects? Laravel vs CodeIgniter: Which framework is better for large projects? Jun 04, 2024 am 09:09 AM

When choosing a framework for large projects, Laravel and CodeIgniter each have their own advantages. Laravel is designed for enterprise-level applications, offering modular design, dependency injection, and a powerful feature set. CodeIgniter is a lightweight framework more suitable for small to medium-sized projects, emphasizing speed and ease of use. For large projects with complex requirements and a large number of users, Laravel's power and scalability are more suitable. For simple projects or situations with limited resources, CodeIgniter's lightweight and rapid development capabilities are more ideal.

Which one is more beginner-friendly, Laravel or CodeIgniter? Which one is more beginner-friendly, Laravel or CodeIgniter? Jun 05, 2024 pm 07:50 PM

For beginners, CodeIgniter has a gentler learning curve and fewer features, but covers basic needs. Laravel offers a wider feature set but has a slightly steeper learning curve. In terms of performance, both Laravel and CodeIgniter perform well. Laravel has more extensive documentation and active community support, while CodeIgniter is simpler, lightweight, and has strong security features. In the practical case of building a blogging application, Laravel's EloquentORM simplifies data manipulation, while CodeIgniter requires more manual configuration.

Questions and Answers on PHP Enterprise Application Microservice Architecture Design Questions and Answers on PHP Enterprise Application Microservice Architecture Design May 07, 2024 am 09:36 AM

Microservice architecture uses PHP frameworks (such as Symfony and Laravel) to implement microservices and follows RESTful principles and standard data formats to design APIs. Microservices communicate via message queues, HTTP requests, or gRPC, and use tools such as Prometheus and ELKStack for monitoring and troubleshooting.

Laravel vs CodeIgniter: Which framework is better for small projects? Laravel vs CodeIgniter: Which framework is better for small projects? Jun 04, 2024 pm 05:29 PM

For small projects, Laravel is suitable for larger projects that require strong functionality and security. CodeIgniter is suitable for very small projects that require lightweight and ease of use.

See all articles