PHPExcel是一個(gè)非常方便生成Excel格式文件的類(lèi),官方下載包中帶有大量如何生成各種樣式excel文件的示例,但沒(méi)有一個(gè)讀取Excel文件的完整例子.Xiaoqiang根據(jù)網(wǎng)上的資料,整理了一份簡(jiǎn)單讀取Excel文件的例子. 傳統(tǒng)方法: <?php/**
*
* @copyright 2007-2012 Xiaoqiang.
* @author Xiaoqiang.Wu <jamblues@gmail.com>
* @version 1.01
*/ error_reporting(E_ALL); date_default_timezone_set('Asia/ShangHai'); /** PHPExcel_IOFactory */require_once '../Classes/PHPExcel/IOFactory.php';
// Check prerequisitesif (!file_exists("31excel5.xls")) {
exit("not found 31excel5.xls.\n");} $reader = PHPExcel_IOFactory::createReader('Excel5'); //設(shè)置以Excel5格式(Excel97-2003工作簿)$PHPExcel = $reader->load("31excel5.xls"); // 載入excel文件$sheet = $PHPExcel->getSheet(0); // 讀取第一個(gè)工作表$highestRow = $sheet->getHighestRow(); // 取得總行數(shù)$highestColumm = $sheet->getHighestColumn(); // 取得總列數(shù)$highestColumm= PHPExcel_Cell::columnIndexFromString($colsNum); //字母列轉(zhuǎn)換為數(shù)字列 如:AA變?yōu)?7 /** 循環(huán)讀取每個(gè)單元格的數(shù)據(jù) */for ($row = 1; $row <= $highestRow; $row++){//行數(shù)是以第1行開(kāi)始
for ($column = 0; $column < $highestColumm; $column++) {//列數(shù)是以第0列開(kāi)始
$columnName = PHPExcel_Cell::stringFromColumnIndex($column);
echo $columnName.$row.":".$sheet->getCellByColumnAndRow($column, $row)->getValue()."<br />";
}} ?> |
精簡(jiǎn)方法: <?php/**
*
* @copyright 2007-2012 Xiaoqiang.
* @author Xiaoqiang.Wu <jamblues@gmail.com>
* @version 1.01
*/ error_reporting(E_ALL); date_default_timezone_set('Asia/ShangHai'); /** PHPExcel_IOFactory */require_once '../Classes/PHPExcel/IOFactory.php';
// Check prerequisitesif (!file_exists("31excel5.xls")) {
exit("not found 31excel5.xls.\n");} $reader = PHPExcel_IOFactory::createReader('Excel5'); //設(shè)置以Excel5格式(Excel97-2003工作簿)$PHPExcel = $reader->load("31excel5.xls"); // 載入excel文件$sheet = $PHPExcel->getSheet(0); // 讀取第一個(gè)工作表$highestRow = $sheet->getHighestRow(); // 取得總行數(shù)$highestColumm = $sheet->getHighestColumn(); // 取得總列數(shù) /** 循環(huán)讀取每個(gè)單元格的數(shù)據(jù) */for ($row = 1; $row <= $highestRow; $row++){//行數(shù)是以第1行開(kāi)始
for ($column = 'A'; $column <= $highestColumm; $column++) {//列數(shù)是以A列開(kāi)始
$dataset[] = $sheet->getCell($column.$row)->getValue();
echo $column.$row.":".$sheet->getCell($column.$row)->getValue()."<br />";
}} ?> |
PHPExcel已經(jīng)不再維護(hù),現(xiàn)在更新為PhpSpreadsheet,https://github.com/PHPOffice/PhpSpreadsheet
|