1、composer
composer require phpoffice/phpspreadsheet
2、文件传入方法
public function talentImport(string $file_name='excelFile') { $file = \Illuminate\Support\Facades\Request::file($file_name); if ($file) { if(!$file->isValid()) { return '文件有误'; } if (!in_array($file->getClientOriginalExtension(), ['xls', 'xlsx'])) { return '只允许上传xls或xlsx格式的文件'; } $excel_file_path = $file->getRealPath(); if (!is_uploaded_file($excel_file_path)) { return '非法上传'; } $sheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($excel_file_path)->getActiveSheet(); $res = array(); foreach ($sheet->getRowIterator(2) as $row) { $tmp = array(); foreach ($row->getCellIterator() as $cell) { $tmp[] = $cell->getFormattedValue(); } $res[$row->getRowIndex()] = $tmp; } if (empty($res)) { return '无法读取文件内容或文件内容为空'; } return $res; } return '请上传excel文件'; }
3、对文件内容的数组进行操作
foreach ($res as $row) { 验证数据正确性 存入insert数组 } insert($array)