前端代码:

后端代码:

public function importExcel() { if ($this->request->isPost()) { $file = $this->request->file('excel'); if ($file) { $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads'); if ($info) { $filename = $info->getSaveName(); $inputFileName = ROOT_PATH . 'public' . DS . 'uploads' . DS . $filename; $extension = strtolower(pathinfo($inputFileName, PATHINFO_EXTENSION)); if ($extension == 'xlsx' || $extension == 'xls') { // 读取excel文件 $objPHPExcel = \PHPExcel_IOFactory::load($inputFileName); // 获取第一个工作表 $sheet = $objPHPExcel->getSheet(0); // 获取最大行数 $highestRow = $sheet->getHighestRow(); // 获取最大列数 $highestColumn = $sheet->getHighestColumn(); // 循环读取数据 for ($row = 2; $row <= $highestRow; $row++) { // 读取一行数据 $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, null, true, false); // 处理数据,保存到数据库 $data = [ 'name' => $rowData[0][0], 'age' => $rowData[0][1], 'gender' => $rowData[0][2], 'address' => $rowData[0][3], ]; \app\model\User::create($data); } return '导入成功'; } else { return '文件格式不正确'; } } else { return '文件上传失败'; } } else { return '请选择文件'; } } else { return '请求错误'; }

thinkphp3使用PHPEXCEL 18导入数据库前段和后端代码

原文地址: http://www.cveoy.top/t/topic/g8Ll 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录