Home >Backend Development >PHP Tutorial >PHP uses the PHPExcel class to export and import Excel usage_PHP tutorial
The PHPExcel class is an excel table processing plug-in for PHP. Now I will introduce to you the application method of using the PHPExcel class to import and export excel tables. Friends who need to know more can refer to it for reference (PHPExcel is downloaded from Baidu and will not be introduced here).
Export Excel usage
//Set environment variables (added PHPExcel)
The code is as follows | Copy code | ||||||||
//Note: In yii, you can also directly Yii::import("application.lib.PHPExcel.*" ); //Introducing PHPExcel related files require_once "PHPExcel.php"; require_once 'PHPExcel/IOFactory.php'; require_once 'PHPExcel/Writer/ Excel5.php';
|
//Put the content to be exported into the table
The code is as follows | Copy code | ||||
//Set parameters //Set value $resultPHPExcel->getActiveSheet()->setCellValue('A1' , 'Quarterly'); $resultPHPExcel->getActiveSheet()->setCellValue('B1', 'Name'); $resultPHPExcel->getActiveSheet()->setCellValue(' C1', 'Quantity'); $i = 2; foreach($data as $item){ $resultPHPExcel->getActiveSheet()->setCellValue('A' . $i, $item['quarter']); $resultPHPExcel->getActiveSheet()->setCellValue('B' . $i, $item['name']); $resultPHPExcel->getActiveSheet()->setCellValue('C' . $i, $item['number']); $i ++; } |
The code is as follows | Copy code |
//Set the export file name $outputFileName = 'total.xls'; $xlsWriter = new PHPExcel_Writer_Excel5($resultPHPExcel); //ob_start(); ob_flush(); header("Content-Type: application/force-download"); header("Content-Type: application/octet-stream"); header("Content-Type: application/download"); header('Content-Disposition :inline;filename="'.$outputFileName.'"'); header("Content-Transfer-Encoding: binary"); header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Pragma: no-cache"); $xlsWriter->save( "php://output" ); |
The output is wrong.
The default $xlsWriter->save( "php://output" ); may be incomplete because the cache is not large enough, so make a transfer as follows:
The code is as follows | Copy code td> | ||||
|
//file_get_contents() function reads the entire file into a string. Same as file(), except that file_get_contents() reads the file into a string.
Import Excel usage
Copy code | |
if($_POST['leadExcel'] == "true") { { //Get the extension of the uploaded file // Read the excel file in a cycle, read one, insert a /* 第二种方法*/ |
HTML网页代码
代码如下
|
复制代码 | ||||