search
HomeBackend DevelopmentPHP TutorialPHP import and export excel files

To operate excel tables, you need to use the PHPExcel plug-in. Since I generally use the CI framework, I will introduce it with the CI framework.

First, introduce the relevant files of PHPExcel:

$this->load->library('PHPExcel/IOFactory');
$this->load->model('search_model');
Next, we will introduce how to export the excel file. First, create a new worksheet and initialize it:

//新建工作表
$objPHPExcel = new PHPExcel();
// 操作第一个工作表 
$objPHPExcel->setActiveSheetIndex(0); 
// 设置工作薄名称 
$objPHPExcel->getActiveSheet()->setTitle("集合"); 
// 设置默认字体和大小 
$objPHPExcel->getDefaultStyle()->getFont()->setName("宋体"); 
$objPHPExcel->getDefaultStyle()->getFont()->setSize(10); 
Then set the header, of course, you can not set it, setCellValueByColumnAndRow( The first parameter of the $col, $row, $name) method is the column of the operation (starting at 0), the second parameter is the row of the operation (starting at 1), and the third parameter is the value you want to set. :

$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(0, 1, " ");
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(1, 1, "IMSI");
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(2, 1, "IMEI");
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(3, 1, "设备号");
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(4, 1, "号段");
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(5, 1, "归属地");
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(6, 1, "运营商");
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(7, 1, "时间");
After setting the header, start assigning values ​​line by line. The operation method is the same as above:

$row = 2;
$i = 0;
foreach($data as $item){
	$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(0, $row, $i+1);
	$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(1, $row, $item['QQ']);
	$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(2, $row, $item['MSN']);
	$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(3, $row, $item['DeviceID']);
	$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(4, $row, $item['RTX']);
	$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(5, $row, $item['Area']);
	$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(6, $row, $item['Type']);
	$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(7, $row, $item['TimeStamp']);
	$row++;
	$i++;
}
Finally, output the file to the page for download:

$objWriter = IOFactory::createWriter($objPHPExcel, 'Excel5');     
ob_end_clean();
header("Pragma: public");     
header("Expires: 0");    
header("Cache-Control:must-revalidate, post-check=0, pre-check=0");     
header("Content-Type:application/force-download");     
header("Content-Type: application/vnd.ms-excel;charset=UTF-8");     
header("Content-Type:application/octet-stream");     
header("Content-Type:application/download");     
header("Content-Disposition:attachment;filename=result.xls"); //定义文件名   
header("Content-Transfer-Encoding:binary");     
$objWriter->save("php://output");
The import method is also similar, First upload the file to the background, get the path and then open excel:

$orig_name = explode('.',$upload_data['orig_name'])[0];//原始文件名
$extend=strrchr ($upload_data['file_name'],'.'); //获取文件类型
$readerType = ($extend == ".xlsx") ? "Excel2007" : "Excel5";
$path = $config['upload_path'].$upload_data['file_name']; //文件路径
$objPHPExcel = new IOFactory();
$objReader = $objPHPExcel::createReader($readerType)->load($path);
$sheet = $objReader->getSheet( 0 );

Then read the data in a loop and store it in the database:

$highestRow = $sheet->getHighestRow(); // 取得总行数 但是很多无数据的空白行也读取了,所以未采用此方法
$highestColumn = $sheet->getHighestColumn(); // 取得总列数
$colspan = range( 'A', $highestColumn );

$rowArray = $sheet->getRowDimensions();// 取得总行数 
$rowCount = count($rowArray);
//循环读取excel文件(因为第一行我一般都加了表头,所以总是从第二行开始读数据)
for ( $j = 2; $j getActiveSheet()->getCell( $value . $j )->getValue();
	}
	
	//插入表中
	$sql = "insert into im_blacklist(`name`,`MAC`,`IMSI`,`IMEI`,`groupid`) values('".$array[1]."','".$array[2]."',".$array[3].",".$array[4].",".$id.")";
	$this->db->query($sql);
}
However, when reading this method, it is related to the row where the excel cursor is located. It is best to open excel, move the cursor to the lower right corner of the table, and then close excel to perform the reading operation. Only then can all data be read correctly.


The above introduces the import and export of excel files in PHP, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.

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
How do you modify data stored in a PHP session?How do you modify data stored in a PHP session?Apr 27, 2025 am 12:23 AM

TomodifydatainaPHPsession,startthesessionwithsession_start(),thenuse$_SESSIONtoset,modify,orremovevariables.1)Startthesession.2)Setormodifysessionvariablesusing$_SESSION.3)Removevariableswithunset().4)Clearallvariableswithsession_unset().5)Destroythe

Give an example of storing an array in a PHP session.Give an example of storing an array in a PHP session.Apr 27, 2025 am 12:20 AM

Arrays can be stored in PHP sessions. 1. Start the session and use session_start(). 2. Create an array and store it in $_SESSION. 3. Retrieve the array through $_SESSION. 4. Optimize session data to improve performance.

How does garbage collection work for PHP sessions?How does garbage collection work for PHP sessions?Apr 27, 2025 am 12:19 AM

PHP session garbage collection is triggered through a probability mechanism to clean up expired session data. 1) Set the trigger probability and session life cycle in the configuration file; 2) You can use cron tasks to optimize high-load applications; 3) You need to balance the garbage collection frequency and performance to avoid data loss.

How can you trace session activity in PHP?How can you trace session activity in PHP?Apr 27, 2025 am 12:10 AM

Tracking user session activities in PHP is implemented through session management. 1) Use session_start() to start the session. 2) Store and access data through the $_SESSION array. 3) Call session_destroy() to end the session. Session tracking is used for user behavior analysis, security monitoring, and performance optimization.

How can you use a database to store PHP session data?How can you use a database to store PHP session data?Apr 27, 2025 am 12:02 AM

Using databases to store PHP session data can improve performance and scalability. 1) Configure MySQL to store session data: Set up the session processor in php.ini or PHP code. 2) Implement custom session processor: define open, close, read, write and other functions to interact with the database. 3) Optimization and best practices: Use indexing, caching, data compression and distributed storage to improve performance.

Explain the concept of a PHP session in simple terms.Explain the concept of a PHP session in simple terms.Apr 26, 2025 am 12:09 AM

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

How do you loop through all the values stored in a PHP session?How do you loop through all the values stored in a PHP session?Apr 26, 2025 am 12:06 AM

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

Explain how to use sessions for user authentication.Explain how to use sessions for user authentication.Apr 26, 2025 am 12:04 AM

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

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

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment