


Laravel 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!

Hot AI Tools

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

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

Undress AI Tool
Undress images for free

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)

Hot Topics











LaravelEloquent Model Retrieval: Easily obtaining database data EloquentORM provides a concise and easy-to-understand way to operate the database. This article will introduce various Eloquent model search techniques in detail to help you obtain data from the database efficiently. 1. Get all records. Use the all() method to get all records in the database table: useApp\Models\Post;$posts=Post::all(); This will return a collection. You can access data using foreach loop or other collection methods: foreach($postsas$post){echo$post->

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

When developing websites using CraftCMS, you often encounter resource file caching problems, especially when you frequently update CSS and JavaScript files, old versions of files may still be cached by the browser, causing users to not see the latest changes in time. This problem not only affects the user experience, but also increases the difficulty of development and debugging. Recently, I encountered similar troubles in my project, and after some exploration, I found the plugin wiejeben/craft-laravel-mix, which perfectly solved my caching problem.

Laravel provides a comprehensive Auth framework for implementing user login functions, including: Defining user models (Eloquent model), creating login forms (Blade template engine), writing login controllers (inheriting Auth\LoginController), verifying login requests (Auth::attempt) Redirecting after login is successful (redirect) considering security factors: hash passwords, anti-CSRF protection, rate limiting and security headers. In addition, the Auth framework also provides functions such as resetting passwords, registering and verifying emails. For details, please refer to the Laravel documentation: https://laravel.com/doc

Efficiently process 7 million records and create interactive maps with geospatial technology. This article explores how to efficiently process over 7 million records using Laravel and MySQL and convert them into interactive map visualizations. Initial challenge project requirements: Extract valuable insights using 7 million records in MySQL database. Many people first consider programming languages, but ignore the database itself: Can it meet the needs? Is data migration or structural adjustment required? Can MySQL withstand such a large data load? Preliminary analysis: Key filters and properties need to be identified. After analysis, it was found that only a few attributes were related to the solution. We verified the feasibility of the filter and set some restrictions to optimize the search. Map search based on city

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

How does Laravel play a role in backend logic? It simplifies and enhances backend development through routing systems, EloquentORM, authentication and authorization, event and listeners, and performance optimization. 1. The routing system allows the definition of URL structure and request processing logic. 2.EloquentORM simplifies database interaction. 3. The authentication and authorization system is convenient for user management. 4. The event and listener implement loosely coupled code structure. 5. Performance optimization improves application efficiency through caching and queueing.

Want to learn the Laravel framework, but suffer from no resources or economic pressure? This article provides you with free learning of Laravel, teaching you how to use resources such as online platforms, documents and community forums to lay a solid foundation for your PHP development journey from getting started to master.
