How to use PHPExcel to process Excel files?
PHPExcel is an open source PHP library for processing Microsoft Excel (.xls and .xlsx) files. It can read, write and operate Excel files, and provides a wealth of functions and methods.
Using the PHPExcel library in PHP projects can quickly and easily process Excel files and implement functions such as data import, export and data processing. This article will introduce how to use PHPExcel to process Excel files.
1. Install PHPExcel
To use PHPExcel, you need to download and install the library first. The latest version of PHPExcel can be downloaded from the official website (https://github.com/PHPOffice/PHPExcel). After decompressing the compressed package, place the PHPExcel folder into the project, and then introduce PHPExcel's automatic loading file into the PHP file:
require_once 'PHPExcel/Classes/PHPExcel.php';
2. Create Excel files
Use PHPExcel to quickly create Excel file and write data. The following is a sample code to create an Excel document containing three rows and three columns and write data:
$excel = new PHPExcel(); $excel->setActiveSheetIndex(0); $excel->getActiveSheet()->setCellValue('A1', '姓名') ->setCellValue('B1', '年龄') ->setCellValue('C1', '邮箱'); $excel->getActiveSheet()->setCellValue('A2', '张三') ->setCellValue('B2', 20) ->setCellValue('C2', 'zhangsan@example.com'); $excel->getActiveSheet()->setCellValue('A3', '李四') ->setCellValue('B3', 25) ->setCellValue('C3', 'lisi@example.com'); $excel->getActiveSheet()->setCellValue('A4', '王五') ->setCellValue('B4', 30) ->setCellValue('C4', 'wangwu@example.com'); header('Content-Type: application/vnd.ms-excel'); header('Content-Disposition: attachment;filename="example.xls"'); header('Cache-Control: max-age=0'); $writer = PHPExcel_IOFactory::createWriter($excel, 'Excel5'); $writer->save('php://output');
In this code, a PHPExcel object named $excel is first created and then defaulted to The worksheet is set to the first worksheet (index 0). Then write the data to the Excel worksheet through the setCellValue() method.
Finally set the file type, file name, cache control and other attributes of the Excel file to be output, and create an instance object $writer of PHPExcel_IOFactory to write the Excel object $excel to the output.
3. Reading Excel files
Use PHPExcel to easily read data in Excel files. The following is a sample code for reading an Excel file:
$objReader = PHPExcel_IOFactory::createReader('Excel5'); $objReader->setReadDataOnly(true); $objPHPExcel = $objReader->load("example.xls"); $worksheet = $objPHPExcel->getActiveSheet(); foreach ($worksheet->getRowIterator() as $row) { $cellIterator = $row->getCellIterator(); $cellIterator->setIterateOnlyExistingCells(false); $columns = []; foreach ($cellIterator as $cell) { $columns[] = $cell->getValue(); } if (count($columns) > 0) { echo implode('|', $columns) . " "; } }
In this code, first use the createReader() method of the PHPExcel_IOFactory class to create an Excel reader object $objReader, and then use the load() method to load the Excel The file example.xls is loaded into memory and finally the first worksheet in the Excel file is obtained.
Then traverse the cells in each row and column, use the getValue() method to obtain the value in each cell, and concatenate all the data in each row into a string.
Finally output the data of each row.
4. Export Excel file
Use PHPExcel to export data to an Excel file. The following is a sample code to export data in the MySQL database to an Excel file:
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password'); $sql = "SELECT name, age, email FROM users"; $stmt = $pdo->query($sql); $excel = new PHPExcel(); $excel->setActiveSheetIndex(0); $excel->getActiveSheet()->setCellValue('A1', '姓名') ->setCellValue('B1', '年龄') ->setCellValue('C1', '邮箱'); $i = 2; while ($row = $stmt->fetch()) { $excel->getActiveSheet()->setCellValue('A' . $i, $row['name']) ->setCellValue('B' . $i, $row['age']) ->setCellValue('C' . $i, $row['email']); $i++; } header('Content-Type: application/vnd.ms-excel'); header('Content-Disposition: attachment;filename="users.xls"'); header('Cache-Control: max-age=0'); $writer = PHPExcel_IOFactory::createWriter($excel, 'Excel5'); $writer->save('php://output');
In this code, first connect to the MySQL database through the PDO object and query the data in the users table. Then create a PHPExcel object named $excel and write the data of each row into the Excel object in turn.
Finally set the file type, file name, cache control and other attributes of the Excel file to be output, and create an instance object $writer of PHPExcel_IOFactory to write the Excel object $excel to the output.
5. Conclusion
Through the introduction of this article, readers should understand how to use PHPExcel to process Excel files. Using PHPExcel, you can easily read, write and operate Excel files, and at the same time, you can export data from other data sources (such as MySQL database) to Excel files.
Although PHPExcel has ceased maintenance, as a mature and stable Excel processing library, it can still be used in many PHP projects and provides rich sample codes and documentation for reference.
The above is the detailed content of How to use PHPExcel to process Excel files?. 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

AI Hentai Generator
Generate AI Hentai for free.

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



1. First, we right-click the blank space of the taskbar and select the [Task Manager] option, or right-click the start logo, and then select the [Task Manager] option. 2. In the opened Task Manager interface, we click the [Services] tab on the far right. 3. In the opened [Service] tab, click the [Open Service] option below. 4. In the [Services] window that opens, right-click the [InternetConnectionSharing(ICS)] service, and then select the [Properties] option. 5. In the properties window that opens, change [Open with] to [Disabled], click [Apply] and then click [OK]. 6. Click the start logo, then click the shutdown button, select [Restart], and complete the computer restart.

Summary of frequently asked questions about importing Excel data into Mysql: How to deal with error log problems encountered when importing data? Importing Excel data into a MySQL database is a common task. However, during this process, we often encounter various errors and problems. One of them is the error log issue. When we try to import data, the system may generate an error log listing the specific information about the error that occurred. So, how should we deal with the error log when we encounter this situation? First, we need to know how

Quickly learn how to open and process CSV format files. With the continuous development of data analysis and processing, CSV format has become one of the widely used file formats. A CSV file is a simple and easy-to-read text file with different data fields separated by commas. Whether in academic research, business analysis or data processing, we often encounter situations where we need to open and process CSV files. The following guide will show you how to quickly learn to open and process CSV format files. Step 1: Understand the CSV file format First,

In the process of PHP development, dealing with special characters is a common problem, especially in string processing, special characters are often escaped. Among them, converting special characters into single quotes is a relatively common requirement, because in PHP, single quotes are a common way to wrap strings. In this article, we will explain how to handle special character conversion single quotes in PHP and provide specific code examples. In PHP, special characters include but are not limited to single quotes ('), double quotes ("), backslash (), etc. In strings

How to deal with data normalization issues in C++ development. In C++ development, we often need to process various types of data, which often have different value ranges and distribution characteristics. To use this data more efficiently, we often need to normalize it. Data normalization is a data processing technique that maps data of different scales to the same scale range. In this article, we will explore how to deal with data normalization issues in C++ development. The purpose of data normalization is to eliminate the dimensional influence between data and map the data to

How to handle XML and JSON data formats in C# development requires specific code examples. In modern software development, XML and JSON are two widely used data formats. XML (Extensible Markup Language) is a markup language used to store and transmit data, while JSON (JavaScript Object Notation) is a lightweight data exchange format. In C# development, we often need to process and operate XML and JSON data. This article will focus on how to use C# to process these two data formats, and attach

How to crawl and process data by calling API interface in PHP project? 1. Introduction In PHP projects, we often need to crawl data from other websites and process these data. Many websites provide API interfaces, and we can obtain data by calling these interfaces. This article will introduce how to use PHP to call the API interface to crawl and process data. 2. Obtain the URL and parameters of the API interface. Before starting, we need to obtain the URL of the target API interface and the required parameters.

The Java.lang.UnsatisfiedLinkError exception occurs at runtime when an attempt to access or load a native method or library fails due to a mismatch between its architecture, operating system, or library path configuration and the referenced one. It usually indicates that there is an incompatibility with the architecture, operating system configuration, or path configuration that prevents success - usually the local library referenced does not match the library installed on the system and is not available at runtime. To overcome this error, the key is to be native The library is compatible with your system and can be accessed through its library path setting. You should verify that library files exist in their specified locations and meet system requirements. java.lang.UnsatisfiedLinkErrorjava.lang
