首先下载:PHPExcel.php
https://codeload.github.com/PHPOffice/PHPExcel/zip/1.8
<?php namespace app\api\controller; use app\common\controller\Api; use think\Db; /*导入接口*/ class Import extends Api { public function index(){ /*引入PHPExcel插件*/ require_once(VENDOR_PATH .'/phpExcel/PHPExcel-1.8/PHPExcel-1.8/Classes/PHPExcel.php'); /**加载excel文件*/ $file_name = request()->file('file'); if(empty($file_name)){ $this->error('请求失败,未识别到文件'); } $info = $file_name->validate(['size'=>1567800,'ext'=>'xlsx,xls,csv'])->move(ROOT_PATH . 'public' . DS . 'excel'); $exclePath = $info->getSaveName(); //获取文件名 $filename = ROOT_PATH . 'public' . DS . 'excel' . DS . $exclePath; /**上传文件的地址*/ $objPHPExcel = \PHPExcel_IOFactory::load($filename,$encode='utf-8'); $sheet = $objPHPExcel->getSheet(0); $highestRow = $sheet->getHighestRow(); /**取得总行数*/ $highestColumn = $sheet->getHighestColumn(); /**取得总列数*/ $arr = array('A','B','C','D','E','F','G','H','I','J','K','L','M', 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z'); /**一次读取一列*/ $res_arr = array(); for ($row = 2; $row <= $highestRow; $row++) { $row_arr = array(); for ($column = 0; $arr[$column] != 'H'; $column++) { $val = $sheet->getCellByColumnAndRow($column, $row)->getValue(); $row_arr[] = $val; } $res_arr[] = $row_arr; } foreach($res_arr as $k=>$v) { // $data[$k]['birthday'] = date('Y-m-d',strtotime(strlen($v[3])==15 ?('19'. substr($v[3],6,6)):substr($v[3],6,8))); /**生日*/ // $data[$k]['birthday'] = trim($v[1]); $data[$k]['address'] = trim($v[1]); /**籍贯*/ $data[$k]['record'] = trim($v[2]); /**学历*/ $data[$k]['gradeid'] = trim($v[3]); /**岗位档级*/ $data[$k]['base_pay'] = trim($v[4]); /**档级工资*/ $data[$k]['name'] = trim($v[5]); /**名称*/ $data[$k]['tel'] = trim($v[6]); /**手机号*/ // if(!empty($money)){ // $data[$k]['gradeid'] = $v[6]; /**岗位档级*/ // $data[$k]['base_pay'] = $money; /**岗位档级*/ // } } /**开启事务*/ Db::startTrans(); $catch = []; $ok = 0; $error = 0; foreach ($data as $key=>$value){ try { $success = db('staffs')->insert($value); /**插入数据*/ if (!empty($success)) { Db::commit(); $ok++; }else{ $error++; $catch[] = ['name'=>$value['name'],'tel'=>$value['tel']]; } } catch (\Exception $e) { $catch[] = ['name'=>$value['name'],'tel'=>$value['tel']]; Db::rollback(); $error++; } } $total = count($res_arr); $this->success("总{$total}条,成功{$ok}条,失败{$error}条。",$catch); } }