


Laravel development: How to import and export Excel files using Laravel Excel?
Jun 15, 2023 pm 04:13 PMLaravel 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 數(shù)據(jù)已成功導(dǎo)入!'); } }
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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

There are three main ways to set environment variables in PHP: 1. Global configuration through php.ini; 2. Passed through a web server (such as SetEnv of Apache or fastcgi_param of Nginx); 3. Use putenv() function in PHP scripts. Among them, php.ini is suitable for global and infrequently changing configurations, web server configuration is suitable for scenarios that need to be isolated, and putenv() is suitable for temporary variables. Persistence policies include configuration files (such as php.ini or web server configuration), .env files are loaded with dotenv library, and dynamic injection of variables in CI/CD processes. Security management sensitive information should be avoided hard-coded, and it is recommended to use.en

Laravel's configuration cache improves performance by merging all configuration files into a single cache file. Enabling configuration cache in a production environment can reduce I/O operations and file parsing on each request, thereby speeding up configuration loading; 1. It should be enabled when the application is deployed, the configuration is stable and no frequent changes are required; 2. After enabling, modify the configuration, you need to re-run phpartisanconfig:cache to take effect; 3. Avoid using dynamic logic or closures that depend on runtime conditions in the configuration file; 4. When troubleshooting problems, you should first clear the cache, check the .env variables and re-cache.

To enable PHP containers to support automatic construction, the core lies in configuring the continuous integration (CI) process. 1. Use Dockerfile to define the PHP environment, including basic image, extension installation, dependency management and permission settings; 2. Configure CI/CD tools such as GitLabCI, and define the build, test and deployment stages through the .gitlab-ci.yml file to achieve automatic construction, testing and deployment; 3. Integrate test frameworks such as PHPUnit to ensure that tests are automatically run after code changes; 4. Use automated deployment strategies such as Kubernetes to define deployment configuration through the deployment.yaml file; 5. Optimize Dockerfile and adopt multi-stage construction

Laravel's EloquentScopes is a tool that encapsulates common query logic, divided into local scope and global scope. 1. The local scope is defined with a method starting with scope and needs to be called explicitly, such as Post::published(); 2. The global scope is automatically applied to all queries, often used for soft deletion or multi-tenant systems, and the Scope interface needs to be implemented and registered in the model; 3. The scope can be equipped with parameters, such as filtering articles by year or month, and corresponding parameters are passed in when calling; 4. Pay attention to naming specifications, chain calls, temporary disabling and combination expansion when using to improve code clarity and reusability.

Select logging method: In the early stage, you can use the built-in error_log() for PHP. After the project is expanded, be sure to switch to mature libraries such as Monolog, support multiple handlers and log levels, and ensure that the log contains timestamps, levels, file line numbers and error details; 2. Design storage structure: A small amount of logs can be stored in files, and if there is a large number of logs, select a database if there is a large number of analysis. Use MySQL/PostgreSQL to structured data. Elasticsearch Kibana is recommended for semi-structured/unstructured. At the same time, it is formulated for backup and regular cleaning strategies; 3. Development and analysis interface: It should have search, filtering, aggregation, and visualization functions. It can be directly integrated into Kibana, or use the PHP framework chart library to develop self-development, focusing on the simplicity and ease of interface.

Createahelpers.phpfileinapp/HelperswithcustomfunctionslikeformatPrice,isActiveRoute,andisAdmin.2.Addthefiletothe"files"sectionofcomposer.jsonunderautoload.3.Runcomposerdump-autoloadtomakethefunctionsgloballyavailable.4.Usethehelperfunctions

UseMockeryforcustomdependenciesbysettingexpectationswithshouldReceive().2.UseLaravel’sfake()methodforfacadeslikeMail,Queue,andHttptopreventrealinteractions.3.Replacecontainer-boundserviceswith$this->mock()forcleanersyntax.4.UseHttp::fake()withURLp

This article aims to explore how to use EloquentORM to perform advanced conditional query and filtering of associated data in the Laravel framework to solve the need to implement "conditional connection" in database relationships. The article will clarify the actual role of foreign keys in MySQL, and explain in detail how to apply specific WHERE clauses to the preloaded association model through Eloquent's with method combined with closure functions, so as to flexibly filter out relevant data that meets the conditions and improve the accuracy of data retrieval.
