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

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

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,
'Excel' => MaatwebsiteExcelFacadesExcel::class,

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"

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

config/excel.php
resources/views/vendor/excel

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',

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

'cache' => [
    'enabled' => true,
    'driver' => 'laravel',
],

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(),

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,
],

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,
],

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');
    }
}

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();
    }
}

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 数据已成功导入!');
    }
}

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])
        ]);
    }
}

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
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
Tech Troubles: Ensuring Equitable Access to Tools and Resources for Distributed Team MembersTech Troubles: Ensuring Equitable Access to Tools and Resources for Distributed Team MembersApr 29, 2025 am 12:40 AM

Methods to ensure that distributed team members have fair access to tools and resources include: 1) using low-bandwidth alternatives, such as asynchronous video or text updates, to solve connection problems; 2) setting up core overlapping working hours and providing flexible working hours to manage time zone differences; 3) adapt to different cultural needs through translation functions and cultural awareness training. These strategies help create an inclusive and efficient remote working environment.

Instant Messaging Must-Haves: Fostering Real-Time Communication in Remote SettingsInstant Messaging Must-Haves: Fostering Real-Time Communication in Remote SettingsApr 29, 2025 am 12:38 AM

Forenhancingremotecollaboration,aninstantmessagingtoolmusthave:1)reliabilityforconsistentmessagedelivery,2)anintuitiveuserinterfaceforeasynavigation,3)real-timenotificationstostayupdated,4)seamlessfilesharingforefficientdocumentexchange,5)integration

Have you ever faced any challenges while working in distributed teams?Have you ever faced any challenges while working in distributed teams?Apr 29, 2025 am 12:35 AM

Thebiggestchallengeofmanagingdistributedteamsiscommunication.Toaddressthis,usetoolslikeSlack,Zoom,andGitHub;setclearexpectations;fostertrustandautonomy;implementasynchronousworkpatterns;andintegratetaskmanagementwithcommunicationplatformsforefficient

What are the security improvements in the new Laravel version?What are the security improvements in the new Laravel version?Apr 29, 2025 am 12:17 AM

Laravel's latest version has significantly improved security, including: 1. Enhanced CSRF protection, through a more robust token verification mechanism; 2. Improved SQL injection protection, through an enhanced query construction method; 3. Better session encryption to ensure user data security; 4. Improved authentication system, supporting finer granular user authentication and multi-factor authentication (MFA).

Time Zone Tango: Navigating Scheduling Conflicts in a Global WorkforceTime Zone Tango: Navigating Scheduling Conflicts in a Global WorkforceApr 29, 2025 am 12:13 AM

Tonavigateschedulingconflictsinaglobalworkforce,usetechnology,empathy,andstrategicplanning:1)EmploytoolslikeWorldTimeBuddyorCalendlyforscheduling;2)Rotatemeetingtimestoensurefairness;3)Establishcorehoursforoverlap;4)Beculturallysensitiveandflexiblewi

Full-Stack Development with Laravel: Managing APIs and Frontend LogicFull-Stack Development with Laravel: Managing APIs and Frontend LogicApr 28, 2025 am 12:22 AM

In Laravel full-stack development, effective methods for managing APIs and front-end logic include: 1) using RESTful controllers and resource routing management APIs; 2) processing front-end logic through Blade templates and Vue.js or React; 3) optimizing performance through API versioning and paging; 4) maintaining the separation of back-end and front-end logic to ensure maintainability and scalability.

Lost in Translation: Cultural Nuances and Misunderstandings in Distributed TeamsLost in Translation: Cultural Nuances and Misunderstandings in Distributed TeamsApr 28, 2025 am 12:22 AM

Totackleculturalintricaciesindistributedteams,fosteranenvironmentcelebratingdifferences,bemindfulofcommunication,andusetoolsforclarity.1)Implementculturalexchangesessionstosharestoriesandtraditions.2)Adjustcommunicationmethodstosuitculturalpreference

Measuring Connection: Analytics and Insights for Remote Communication EffectivenessMeasuring Connection: Analytics and Insights for Remote Communication EffectivenessApr 28, 2025 am 12:16 AM

Toassesstheeffectivenessofremotecommunication,focuson:1)Engagementmetricslikemessagefrequencyandresponsetime,2)Sentimentanalysistogaugeemotionaltone,3)Meetingeffectivenessthroughattendanceandactionitems,and4)Networkanalysistounderstandcommunicationpa

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),