1. 安装phpexcel
composer require phpoffice/phpexcel
composer update
2. 前端
<form class="forms-sample" action="../../xxxx/xxxx/do_import_users" method="post" enctype="multipart/form-data"><div class="control-group row"> <label>Excel表格:</label> <input type="file" name="users_excel"/> </div> <br><button type="submit" class="btn btn-primary mr-2">导入</button>
</form>
3. 后端
use PHPExcel_IOFactory; //通过composer加载的第三方类,直接在头部引入一下就可以/*** 批量新增用户*/public function do_import_users()
{// users_excel为变量名if(!request()->file('users_excel')){return $this->error('请上传excel文件');}$path = request()->file('users_excel');//实例化PHPExcel类$PHPExcel = new \PHPExcel();//默认用excel2007读取excel,若格式不对,则用之前的版本进行读取$PHPReader = new \PHPExcel_Reader_Excel2007();if (!$PHPReader->canRead($path)) {$PHPReader = new \PHPExcel_Reader_Excel5();if (!$PHPReader->canRead($path)) {return $this->error('请上传excel文件');}}//读取Excel文件$PHPExcel = $PHPReader->load($path);//读取excel文件中的第一个工作表$sheet = $PHPExcel->getSheet(0);//取得最大的列号,注意,是列号,不是有多少列,比如Q$allColumn = $sheet->getHighestColumn();//取得最大的行号$allRow = $sheet->getHighestRow();// 第一行是列名,从第二行开始插入for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {//获取B列的值$data = ['number'=>$PHPExcel->getActiveSheet()->getCell("A" . $currentRow)->getValue(),'nickName'=>$PHPExcel->getActiveSheet()->getCell("B" . $currentRow)->getValue(),'name'=>$PHPExcel->getActiveSheet()->getCell("C" . $currentRow)->getValue(),'tel'=>$PHPExcel->getActiveSheet()->getCell("D" . $currentRow)->getValue(),'money'=>$PHPExcel->getActiveSheet()->getCell("E" . $currentRow)->getValue(),'time'=>self::get_date_by_excel($PHPExcel->getActiveSheet()->getCell("F" . $currentRow)->getValue()),'is_pay'=>$PHPExcel->getActiveSheet()->getCell("G" . $currentRow)->getValue(),'shop_name'=>$PHPExcel->getActiveSheet()->getCell("H" . $currentRow)->getValue(),'remarks'=>$PHPExcel->getActiveSheet()->getCell("I" . $currentRow)->getValue(),'status'=>0,'created_at'=>date('Y-m-d')];// 其它操作,比如插入数据库}}/*** excel里的字符串时间转时间*/public static function get_date_by_excel($date){if (!$date || $date == '0000-00-00') return null;$unix_time = \PHPExcel_Shared_Date::ExcelToPHP($date);return gmdate('Y-m-d H:i',$unix_time);}
注:现在主要使用phpoffice/phpspreadsheet库,phpoffice/phpexcel已经不再维护,但本文由于环境无法更新,所以就安装了phpoffice/phpexcel。基本操作一样。
参考:https://www.tpxhm.com/fdetail/725.html
by: 软件工程小施同学