首先composer下载:
composer require phpoffice/phpspreadsheet
在控制器中引用:
use PhpOffice\PhpSpreadsheet\IOFactory;
开始使用,这里是两个字段:
public function importData() { // 获取表单上传文件 $file[] = request()->file('file'); $savename = \think\facade\Filesystem::putFile('file', $file[0]); $fileExtendName = substr(strrchr($savename, '.'), 1); // 有Xls和Xlsx格式两种 if ($fileExtendName == 'xlsx') { $objReader = IOFactory::createReader('Xlsx'); } else { $objReader = IOFactory::createReader('Xls'); } $objReader->setReadDataOnly(TRUE); // 读取文件,tp6默认上传的文件,在runtime的相应目录下,可根据实际情况自己更改 $objPHPExcel = $objReader->load(root_path() . '/runtime/storage/' . $savename); $sheet = $objPHPExcel->getSheet(0); //excel中的第一张sheet $highestRow = $sheet->getHighestRow(); // 取得总行数 $highestColumn = $sheet->getHighestColumn(); // 取得总列数 \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn); $lines = $highestRow - 1; if ($lines <= 0) { return json(['code' => 0, 'message' => '保存失败']); } $data = array(); for ($j = 1; $j <=$highestRow; $j++) { $data[$j] = [ 'name' => trim($objPHPExcel->getActiveSheet()->getCell("A" . $j)->getValue()), 'time' => trim($objPHPExcel->getActiveSheet()->getCell("B" . $j)->getValue()), ]; $rt = Db::name('excel')->insert($data[$j]); } if ($rt !== false) { return json(['code' => 20000, 'message' => '导入成功']); } else { return json(['code' => 0, 'message' => '导入失败']); } }