1. 程式人生 > >PHPExcel將Excel數據導入數據庫

PHPExcel將Excel數據導入數據庫

保存 方法 ksh factory spa tao col 導入 div

 1 <?php
 2 //PHPExcel讀取導入Excel數據到數據庫(2003,2007通用)使用方法:
 3 //先用excel2array()方法將excel表中的數據存儲到數組,在從遍歷二維數組將數據保存進數據庫
 4 require_once "./PHPExcel.class.php";
 5 require_once "./PHPExcel/Cell/DataType.php";
 6 require_once "./PHPExcel/IOFactory.php";
 7 /**
 8  * 將excel表中的數據存儲到數組
 9  * @param string $filename 文件名
10  * @return array
11 */ 12 function excel2array($filename){ 13 $ext = pathinfo($filename, PATHINFO_EXTENSION);//獲取文件後綴名 14 if($ext == "xls"){ 15 $objReader = PHPExcel_IOFactory::createReader(‘Excel5‘); 16 } 17 if($ext == "xlsx"){ 18 $objReader = PHPExcel_IOFactory::createReader(‘Excel2007‘);
19 } 20 21 $objReader->setReadDataOnly(true); 22 $objPHPExcel = $objReader->load($filename); 23 $objWorksheet = $objPHPExcel->getActiveSheet(); 24 $highestRow = $objWorksheet->getHighestRow(); //取得行數 25 $highestColumn = $objWorksheet->getHighestColumn(); 26 $highestColumnIndex
= PHPExcel_Cell::columnIndexFromString($highestColumn); //取得列數 27 $excelData = array(); 28 for ($row = 2; $row <= $highestRow; $row++) { 29 for ($col = 0; $col < $highestColumnIndex; $col++) { 30 $excelData[$row][] =$objWorksheet->getCellByColumnAndRow($col, $row)->getValue(); 31 } 32 } 33 return $excelData; 34 }

PHPExcel將Excel數據導入數據庫