1、composer 下载PHPexcel
composer require phpoffice/phpexcel

2、后端
引入命名空间
use PHPExcel\PHPExcel;
public function clupload()
{
if(request()->isPost()) {
$file = request()->file('file');
// 移动到框架应用根目录/public/uploads/ 目录下
$info = $file->move(
Env::get('root_path') . 'public' . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . 'Excel'
);
if ($info) {
//获取文件所在目录名 注意 tp5.0和tp5.1 分隔符不一样 DS 或者 DIRECTORY_SEPARATOR
//$path=Env::get('root_path') . 'public' . DIRECTORY_SEPARATOR.'uploads'.DIRECTORY_SEPARATOR .'excel/'.$info->getSaveName();
$path = Env::get('root_path') . 'public\uploads\excel\\' . $info->getSaveName();
//获取文件后缀
$suffix = $info->getExtension();
//判断哪种类型
if ($suffix == "xlsx") {
$objReader = \PHPExcel_IOFactory::createReader('Excel2007');
} else {
$objReader = \PHPExcel_IOFactory::createReader('Excel5');
}
// 载入excel文件
$objPHPExcel = $objReader->load($path, $encode = 'utf-8');//获取excel文件
// 读取第一张表
$sheet = $objPHPExcel->getSheet(0);
// 取得总行数
$highestRow = $sheet->getHighestRow();
// 取得总列数
$highestColumn = $sheet->getHighestColumn();
$a = 0;
//将表格里面的数据循环到数组中
for ($i = 2; $i <= $highestRow; $i++) {
//*为什么$i=2? (因为Excel表格第一行应该是姓名,年龄,班级,从第二行开始,才是我们要的数据。)
$data[$a]['c_name'] = $objPHPExcel->getActiveSheet()->getCell("B" . $i)->getValue();
$data[$a]['c_xinhao'] = $objPHPExcel->getActiveSheet()->getCell("C" . $i)->getValue();
$data[$a]['c_gcl'] = $objPHPExcel->getActiveSheet()->getCell("D" . $i)->getValue();
$data[$a]['c_dw'] = $objPHPExcel->getActiveSheet()->getCell("E" . $i)->getValue();
$data[$a]['c_bz'] = $objPHPExcel->getActiveSheet()->getCell("F" . $i)->getValue();
// 这里的数据根据自己表格里面有多少个字段自行决定
$a++;
}
//往数据库添加数据
try {
$res = Db::name('cp')->insertAll($data);
if ($res) {
$this->success('操作成功!');
} else {
$this->success('操作成功!');
}
} catch (Exception $e) {
$this->error($e->getMessage());
}
} else {
// 上传失败获取错误信息
$this->error($file->getError());
}
}
}参考:
https://blog.csdn.net/weixin_62291378/article/details/139181317