public function importData(){
//先執行文件上傳
$file = $this->request->file('files');//獲取表單上傳文件
if(empty($file)){
$this->error('請選擇上傳文件');
}else{
//移動到框架應用根目錄public/excel
$info = $file->move(ROOT_PATH . 'public' . DS . 'Excel');
if($info){
$file_name = ROOT_PATH . 'public' . DS . 'Excel' . DS . $info->getsaveName();
//判斷導入表格後綴格式
$extension = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
vendor("PHPExcel.PHPExcel");
$objPHPExcel = new \PHPExcel();
if($extension == 'xlsx'){
//xlsx後綴
$objReader = \PHPExcel_IOFactory::createReader('Excel2007');
}else{
//xls後綴
$objReader = \PHPExcel_IOFactory::createReader('Excel5');
}
//加載文件內容,編碼utf-8
$obj_PHPExcel = $objReader->load($file_name, $encode = 'utf-8');
$excel_array = $obj_PHPExcel->getsheet(0)->toArray(); //轉換爲數組格式
array_shift($excel_array); //刪除第一個數組(標題);
foreach ($excel_array as $key => $value) {
//根據需求處理
}
}else{
//上傳失敗獲取錯誤信息
$this->error($file->getError());
}
}
}