/** * 导入用户 * @author bzhang */ public function importUserAction() { $request = $this->getRequest(); if ($request->isPost()) { $user = $this->authentication()->getIdentity(); if (empty($_FILES['userList'])) { throw new BusinessException('请选择用户列表文件', 1021); } $fileHandler = new ExcelFileHandler($user->id); $uploader = new Uploader($fileHandler); $data = $uploader->processUpload($_FILES['userList']); $attachment = new AttachmentEntity(); $attachment->exchangeArray($data); $attachment->filepath = str_replace("\\", "/", $attachment->filepath); if (!isset($attachment->filename) || !isset($attachment->filepath)) { throw new BusinessException('用户列表Excel导入失败', 1303); } $userArr = $this->userModel->getUserAndAddressFromExcel($attachment); $this->userModel->batchCreateUsers($userArr); return new UnifyJsonModel(); } $view = new ViewModel(); return $view; }
/** * 根据上传的excel文件获取用户列表信息 * @param AttachmentEntity $attachment * @param int $creatorId * @return array * @throws BusinessException */ public function getUserAndAddressFromExcel(AttachmentEntity $attachment) { require_once ROOT . "/vendor/phpoffice/phpexcel/Classes/PHPExcel.php"; $filePath = ROOT . '/public' . $attachment->getUrl(); $PHPExcel = new PHPExcel(); /**默认用excel2007读取excel,若格式不对,则用之前的版本进行读取*/ $PHPReader = new PHPExcel_Reader_Excel2007(); if (!$PHPReader->canRead($filePath)) { $PHPReader = new PHPExcel_Reader_Excel5(); if (!$PHPReader->canRead($filePath)) { throw new BusinessException('请导入excel格式的报表', 1022); } } $PHPExcel = $PHPReader->load($filePath); /**读取excel文件中的第一个工作表*/ $currentSheet = $PHPExcel->getSheet(0); /**取得一共有多少行*/ $allRow = $currentSheet->getHighestRow(); $userArr = array(); /**从第二行记录开始读取*/ for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) { $user = new UserEntity(); /** 根据导出的Excel格式 */ $mobile = $currentSheet->getCellByColumnAndRow(1, $currentRow)->getFormattedValue(); if (empty($mobile)) { break; } $existUser = $this->getUserByMobile($mobile); if (!empty($existUser)) { $user = $existUser; //更新用户 } else { $user->mobile = $mobile; //新增用户 } $user->username = $currentSheet->getCellByColumnAndRow(0, $currentRow)->getFormattedValue(); $user->is_luck_draw_1 = $currentSheet->getCellByColumnAndRow(2, $currentRow)->getFormattedValue(); $user->is_luck_draw_2 = $currentSheet->getCellByColumnAndRow(3, $currentRow)->getFormattedValue(); $user->is_luck_draw_3 = $currentSheet->getCellByColumnAndRow(4, $currentRow)->getFormattedValue(); $user->is_luck_draw_4 = $currentSheet->getCellByColumnAndRow(5, $currentRow)->getFormattedValue(); $userArr[] = $user; } return $userArr; }