PHP逐行读取Excel的操作方法

后端开发PHP 1403

需要使用核心库: PHPExcel

https://github.com/PHPOffice/PHPExcel

这个库相当强大,官方提供了很多演示代码,都在Examples目录下.

逐行读取Excel的方法

header("Content-type: text/html; charset=utf-8"); 
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

define('EOL',(PHP_SAPI == 'cli') ? PHP_EOL : '<br />');

date_default_timezone_set('Asia/Shanghai');

/** Include PHPExcel_IOFactory */
require_once dirname(__FILE__) . '/../Classes/PHPExcel/IOFactory.php';


if (!file_exists("1.xlsx")) {
	exit("xlsl file missing." . EOL);
}



$objReader = PHPExcel_IOFactory::createReader('Excel2007');

$objReader->setReadDataOnly(true);

$objPHPExcel = $objReader->load("1.xlsx");

$objWorksheet = $objPHPExcel->getActiveSheet();

$highestRow = $objWorksheet->getHighestRow(); 

$highestColumn = $objWorksheet->getHighestColumn(); 


$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn); 

$rows = array();


for ($row = 1; $row <= $highestRow; ++$row) {
 	for ($col = 0; $col <= $highestColumnIndex; ++$col) {
    	$rows[$row][] = $objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
	}
}


var_dump($rows);

Post Comment