🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
### Excel 导入 2018-3-3 需要结合 UploadTools 上传类完成导入操作 **位置:** Common\Tools\ExcelTools.class.php **参数:** * @param $file_path string 文件上传后的路径 * @param $ext string 文件后缀 如:.xls **调用:** ~~~ use Common\Tools\UploadTools; // 调用封装 Upload 上传类 use Common\Tools\ExcelTools; // 调用封装 Excel 操作类 public function import() { $upload = new UploadTools(); $info = $upload->saveFile(); // 上传文件 if (!$info) { $this->error($upload->getError()); } $path = APP_ROOT . $info['file_path']; // 文件上传的路径 $e = new ExcelTools(); $data = $e->importExcel($path, $info['ext']); // 读取Excel内容 dump($data); } ~~~ **完整代码:** ~~~ /* * 导入Excel * * jig 2018-3-3 * @param $file_path string 文件上传后的路径 * @param $ext string 文件后缀 如:.xls * return array; */ public function importExcel($file_path, $ext) { if (!is_file($file_path)) { return false; } if ($ext == 'xls') { $excelReader = \PHPExcel_IOFactory::createReader('Excel5'); } else { $excelReader = \PHPExcel_IOFactory::createReader('Excel2007'); } $excelReader->setReadDataOnly(true); $excelObj = $excelReader->load($file_path); $sheet = $excelObj->getActiveSheet(); $row_num = $sheet->getHighestRow(); $column_num = $sheet->getHighestColumn(); $index = \PHPExcel_Cell::columnIndexFromString($column_num); $data = array(); for ($row = 1; $row <= $row_num; ++$row) { $row_arr = array(); $is_empty_row = 0; for($col = 0; $col < $index; ++$col) { $cell = trim($sheet->getCellByColumnAndRow($col, $row)->getCalculatedValue()); if ((!empty($cell) || $cell != "") && $is_empty_row == 0) { $is_empty_row = 1; } if (is_numeric($cell) && stripos($cell, '.')) { $cell = $cell; //$cell = number_format($cell, 2, '.', ''); } array_push($row_arr, $cell); } if($is_empty_row == 1) { array_push($data, $row_arr); } } return $data; } ~~~