1. 程式人生 > >php 讀取excel檔案 支援 csv、xls、xlsx .thinkphp

php 讀取excel檔案 支援 csv、xls、xlsx .thinkphp

專案需求要匯入 各種excel檔案 支援這三種類型。然後做下記錄方便以後使用。


先是上附件 PHPExcel 檔案 下載地址 百度 https://pan.baidu.com/s/1BmhnYd9arWqFD2jUCHUx8Q


下面我們來程式碼 tp 中放在




目錄大概這樣


控制器這樣寫。



   public function import_xls(){
//         echo 1;die;
//        $data=import_excel('./Upload/excel/simple.xls');
        $data=import_excel(
'./Upload/excel/2.xls'); p($data);die; }

在 config 寫入 

/**
 * 匯入excel檔案
 * @param  string $file excel檔案路徑
 * @return array        excel檔案內容陣列
 */
function import_excel($file){
    // 判斷檔案是什麼格式
    $type = pathinfo($file);
    $type = strtolower($type["extension"]);

//    echo $type;die;
// $type=$type==='xlsx' ? 'Excel2007' : 'Excel5'; if($type=='xlsx'){ $type= 'Excel2007'; }elseif($type=='csv'){ $type='csv'; }else{ $type='Excel5'; } // echo $type;die; ini_set('max_execution_time', '0'); Vendor('PHPExcel.PHPExcel'); // 判斷使用哪種格式
$objReader = PHPExcel_IOFactory::createReader($type); $objPHPExcel = $objReader->load($file); $sheet = $objPHPExcel->getSheet(0); // // 取得總行數 // $highestRow = $sheet->getHighestRow(); // // 取得總列數 // $highestColumn = $sheet->getHighestColumn(); // //迴圈讀取excel檔案,讀取一條,插入一條 // $data=array(); // //從第一行開始讀取資料 // for($j=1;$j<=$highestRow;$j++){ // //從A列讀取資料 // for($k='A';$k<=$highestColumn;$k++){ // // 讀取單元格 // //資料座標 // $address=$k.$j; // //讀取到的資料,儲存到陣列$arr中 // $data[$j][]=$objPHPExcel->getActiveSheet()->getCell($address)->getValue(); // // // $data[$j][]=$objPHPExcel->getActiveSheet()->getCell("$k$j")->getValue(); // } // } foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) { //遍歷工作表 //echo 'Worksheet - ' , $worksheet->getTitle() , PHP_EOL; foreach ($worksheet->getRowIterator() as $key=>$row) { //遍歷行 // echo $row->getRowIndex()."<br/>"; $cellIterator = $row->getCellIterator(); //得到所有列 $cellIterator->setIterateOnlyExistingCells( false); // Loop all cells, even if it is not set foreach ($cellIterator as $cell) { //遍歷列 if (!is_null($cell)) { //如果列不給空就得到它的座標和計算的值 $rows[$key][]= $cell->getCalculatedValue(); } } } } return $rows; }

呼叫  列印 值 




excel 檔案






文章為原創 轉載請註明地址  https://blog.csdn.net/qq_25861247/article/details/80376460