点击查看代码
1. 文件上传验证器类
2. 基础类库层
3. 逻辑层
4. 控制器调用
引入扩展包
composer require phpoffice/phpspreadsheet
1. 文件上传验证器类
<?php
declare(strict_types=1);
namespace app\validate;
use think\Validate;
class Upload extends Validate
{
protected $rule = [
'excel' => 'require|filesize:2097152|fileExt:xls,xlsx',
];
protected $message = [
'excel.require' => '没有文件上传',
'excel.filesize' => '图片大小不能超出2M',
'excel.fileExt' => '只支持xls,xlsx文件',
];
}
2. 基础类库层
<?php
namespace app\lib;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
class Excel
{
public static function readData(string $name, array $field, string $scene = 'excel')
{
try {
$file = request()->file($name);
if (!$file) throw new \Exception('没有文件上传');
validate(\app\validate\Upload::class)->scene($scene)->check([$scene => $file]);
$type = ucfirst($file->getOriginalExtension());
$reader = IOFactory::createReader($type);
$reader->setReadDataOnly(true);
$spreadsheet = $reader->load($file->getRealPath());
$sheet = $spreadsheet->getActiveSheet();
return self::getCellData($sheet, $field);
} catch (\Exception $e) {
return ['code' => $e->getCode(), 'errMsg' => $e->getMessage()];
}
}
private static function getCellData(object $sheet, array $field)
{
$highestColumn = $sheet->getHighestColumn();
$highestRow = $sheet->getHighestRow();
$highestColumnIndex = Coordinate::columnIndexFromString($highestColumn);
$data = [];
for ($row = 2; $row <= $highestRow; $row++) {
$build = [];
for ($col = 1; $col <= $highestColumnIndex; $col++) {
$chr = chr(64 + $col);
$key = $field[$chr] ?? $chr;
$build[$key] = $sheet->getCellByColumnAndRow($col, $row)->getValue();
}
$data[] = $build;
}
return $data;
}
}
3. 逻辑层
<?php
namespace app\logic;
use think\facade\Db;
use app\lib\Excel as LibExcel;
class Excel
{
public static function import(string $name, array $field)
{
$data = LibExcel::readData($name, $field);
Db::name('user')->insertAll($data);
}
}
4. 控制器调用
public function upload()
{
$field = [
'A' => 'name',
'B' => 'score',
];
Excel::import('file', $field);
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!