


Laravel development: How to read and write Excel files using Laravel Excel and PHPOffice?
With the widespread use of Excel files in the business and financial fields, integrating Excel files into web applications has become one of the skills required by developers. Since Laravel is a popular PHP framework, there are many packages in its ecosystem that can help us read and write Excel files. This article will introduce how to use Laravel Excel and PHPOffice library to read and write Excel files in Laravel applications.
What is Laravel Excel?
Laravel Excel is a powerful Excel processing tool developed for the Laravel framework. This tool provides an easy-to-use API that can help us import and export Excel files easily. One of the main advantages of this tool is that it allows direct manipulation of Excel files without relying on Excel software.
Installing Laravel Excel can be done through Composer. Go to the directory of the Laravel project in the terminal and run the following Composer command:
composer require maatwebsite/excel
This command will download the latest version of Laravel Excel from Packagist and automatically complete the installation process.
How to export Excel file using Laravel Excel?
Laravel Excel provides an Excel class, which is a proxy class through which you can create new Excel files or open and edit existing Excel files. We can use this class to export Excel files in Laravel application.
Create a new Excel file in the project, we can use the following template provided by Laravel Excel:
<?php namespace AppExports; use MaatwebsiteExcelConcernsFromCollection; use MaatwebsiteExcelConcernsWithHeadings; class ExampleExport implements FromCollection, WithHeadings { public function headings(): array { return [ 'ID', 'Name', 'Email', 'Phone', ]; } /** * @return IlluminateSupportCollection */ public function collection() { return User::select('id', 'name', 'email', 'phone')->get(); } }
In the above code, we define a class named ExampleExport. This class uses the FromCollection and WithHeadings interfaces, which provide the methods needed to generate Excel files.
In the headings() method, we define the headers of the Excel file, which are listed in the first row of the Excel worksheet. In the collect() method, we retrieve the user record from the database and return it to the controller that called the class.
To export an Excel file, we can instantiate ExampleExport in the controller method as follows:
public function export() { return Excel::download(new ExampleExport, 'users.xlsx'); }
In the above code, we use the download() method provided by Laravel Excel from ExampleExport exports an Excel file. This method requires two parameters: the first parameter is the ExampleExport instance, and the second parameter is the Excel file name.
When you access the URL of the export method in your browser, you will be prompted to download the users.xlsx file.
How to import Excel files using Laravel Excel?
When reading an Excel file and importing its data into the database, we can use the import() method provided by Laravel Excel. This method accepts three parameters: the file object, the task callback, and the worksheet name.
To demonstrate how to import an Excel file, we will create a class called UserImport as shown below:
<?php namespace AppImports; use AppUser; use MaatwebsiteExcelConcernsToModel; class UserImport implements ToModel { public function model(array $row) { return new User([ 'name' => $row[0], 'email' => $row[1], 'phone' => $row[2], ]); } }
In the above code, we implemented the UserImport class using the ToModel interface. The ToModel interface provides a required model() method, which converts each row of Excel data into a model object. In the above code, we have parsed the first three columns from the Excel file and used them to create a new user record.
Use the import() method in the controller to import the Excel file, as shown below:
public function import(Request $request) { $file = $request->file('file'); Excel::import(new UserImport, $file); return redirect()->back()->with('success', 'Excel file imported successfully.'); }
In the above code, we get the uploaded Excel file object and pass it through Laravel Excel's import( ) method to import it into the UserImport class. If the import is successful, the system will send a redirect response to the user with a success message of "Excel file imported successfully".
How to use PHPOffice library to read and write Excel files?
PHPOffice is a PHP library used to read and write different types of office files, such as Excel, Word and PowerPoint, etc. PHPOffice, unlike Laravel Excel, is not developed for a specific framework and can be used in any PHP application.
Before installing PHPOffice, you need to ensure that the PHP Zip extension and the PHP XML extension are installed.
Use Composer to install the Spreadsheet library of PHPOffice, you can use the following command:
composer require phpoffice/phpspreadsheet
To create a new Excel file, we can use the following code:
<?php use PhpOfficePhpSpreadsheetSpreadsheet; use PhpOfficePhpSpreadsheetWriterXlsx; $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); $sheet->setCellValue('A1', 'Hello World!'); $sheet->setCellValue('B1', 'This is PHPOffice.'); $writer = new Xlsx($spreadsheet); $writer->save('hello.xlsx');
In the above In the code, we first create a new spreadsheet and add "Hello World!" and "This is PHPOffice." cells to the first two columns of its first row. We then save the spreadsheet to the hello.xlsx file.
To open and edit an existing Excel file, we can use the following code:
<?php use PhpOfficePhpSpreadsheetIOFactory; $spreadsheet = IOFactory::load('hello.xlsx'); $sheet = $spreadsheet->getActiveSheet(); $sheet->setCellValue('C1', 'This cell has been added.'); $writer = new Xlsx($spreadsheet); $writer->save('hello.xlsx');
In the above code, we use the IOFactory class to load an existing Excel file from disk. We then opened the file's active worksheet and added a new cell to it. Finally, we save the updates to the original file.
Conclusion
In this article, we introduced how to read and write Excel files in Laravel application using Laravel Excel and PHPOffice library. We learned how to export and import Excel files using Laravel Excel, and how to create, open, and edit existing Excel files using the PHPOffice library. These techniques should make it easier for you to integrate Excel files into your Laravel application.
The above is the detailed content of Laravel development: How to read and write Excel files using Laravel Excel and PHPOffice?. 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











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

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.

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.

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.

The Laravel framework has built-in methods to easily view its version number to meet the different needs of developers. This article will explore these methods, including using the Composer command line tool, accessing .env files, or obtaining version information through PHP code. These methods are essential for maintaining and managing versioning of Laravel applications.

In the Laravel framework version selection guide for beginners, this article dives into the version differences of Laravel, designed to assist beginners in making informed choices among many versions. We will focus on the key features of each release, compare their pros and cons, and provide useful advice to help beginners choose the most suitable version of Laravel based on their skill level and project requirements. For beginners, choosing a suitable version of Laravel is crucial because it can significantly impact their learning curve and overall development experience.
