ThinkPHP 5.1 里做 Excel 导入,完整链路是:接收上传 → 校验文件 → 读取数据 → 字段映射与校验 → 批量入库 → 返回结果。这篇给出可直接运行的控制器与模型代码。
一、安装
composer require phpoffice/phpexcel
# 目录:vendor/phpoffice/phpexcel/Classes/PHPExcel.php
二、控制器:上传与导入
namespace app\index\controller;
use think\Controller;
use think\Db;
use think\facade\Request;
class Excel extends Controller
{
public function import()
{
// 1. 接收文件
$file = Request::file('file');
if (!$file) {
return json(['code' => 1, 'msg' => '请选择文件']);
}
// 2. 校验扩展名与大小
$ext = strtolower($file->getOriginalExtension());
if (!in_array($ext, ['xls', 'xlsx'])) {
return json(['code' => 1, 'msg' => '只支持 xls/xlsx']);
}
if ($file->getSize() > 5 * 1024 * 1024) {
return json(['code' => 1, 'msg' => '文件不能超过 5MB']);
}
// 3. 移到临时目录
$info = $file->validate(['size' => 5242880])
->move(runtime_path() . 'import/');
if (!$info) {
return json(['code' => 1, 'msg' => $file->getError()]);
}
$path = $info->getPathname();
// 4. 读取
require_once env('root_path') . 'vendor/phpoffice/phpexcel/Classes/PHPExcel.php';
$objPHPExcel = \PHPExcel_IOFactory::load($path);
$sheet = $objPHPExcel->getActiveSheet();
$highestRow = $sheet->getHighestRow();
// 5. 逐行解析(第 1 行是表头,从第 2 行开始)
$rows = [];
$errors = [];
for ($i = 2; $i <= $highestRow; $i++) {
$name = trim((string) $sheet->getCell('A' . $i)->getValue());
$mobile = trim((string) $sheet->getCell('B' . $i)->getValue());
$dept = trim((string) $sheet->getCell('C' . $i)->getValue());
if ($name === '' && $mobile === '') {
continue; // 空行跳过
}
if ($name === '') {
$errors[] = "第 {$i} 行:姓名不能为空";
continue;
}
if (!preg_match('/^1[3-9]\d{9}$/', $mobile)) {
$errors[] = "第 {$i} 行:手机号格式错误";
continue;
}
$rows[] = [
'name' => $name,
'mobile' => $mobile,
'dept' => $dept,
'create_time' => time(),
];
}
// 6. 批量入库(事务)
$success = 0;
if (!empty($rows)) {
Db::startTrans();
try {
foreach (array_chunk($rows, 500) as $chunk) {
Db::name('employee')->insertAll($chunk);
$success += count($chunk);
}
Db::commit();
} catch (\Exception $e) {
Db::rollback();
return json(['code' => 1, 'msg' => '入库失败:' . $e->getMessage()]);
}
}
@unlink($path);
return json([
'code' => 0,
'msg' => "导入完成,成功 {$success} 条",
'data' => ['success' => $success, 'errors' => $errors],
]);
}
}
三、前端上传
<form id="uploadForm">
<input type="file" name="file" accept=".xls,.xlsx">
<button type="submit">导入</button>
</form>
<script>
document.getElementById('uploadForm').onsubmit = async function (e) {
e.preventDefault();
const fd = new FormData(this);
const res = await fetch('/index/excel/import', { method: 'POST', body: fd });
const json = await res.json();
alert(json.msg);
if (json.data.errors.length) console.table(json.data.errors);
};
</script>
四、读取时的注意点
| 问题 | 处理方式 |
|---|---|
| 身份证/手机号变科学计数 | 用 getFormattedValue() 或转字符串 |
| 日期是 5 位数字 | PHPExcel_Shared_Date::ExcelToPHP() 转换 |
| 末尾有大量空行 | getHighestDataRow() 而不是 getHighestRow() |
| 大文件内存爆 | 只读模式 + 分批读 |
// 日期转换示例
$val = $sheet->getCell('D' . $i)->getValue();
if (is_numeric($val)) {
$date = date('Y-m-d', PHPExcel_Shared_Date::ExcelToPHP($val));
}
// 或直接取格式化后的值
$date = $sheet->getCell('D' . $i)->getFormattedValue();
五、总结
导入的核心是「校验前置、批量入库、错误可回溯」:文件类型大小先拦、每行做字段校验、错误的行返回给用户、正确的批量 insert。别忘了 insertAll 分块和事务。
六、导入校验规则表
| 字段 | 规则 | 错误提示 |
|---|---|---|
| name | 必填,2-20 字 | 姓名不能为空或过长 |
| mobile | 1 开头 11 位 | 手机号格式错误 |
| idcard | 18 位,末位可 X | 身份证格式错误 |
| dept | 必须在枚举内 | 部门不存在 |
| date | Y-m-d | 日期格式错误 |
| amount | 数字,≥0 | 金额必须为正数 |
$depts = ['财务', '行政', '法务'];
if (!in_array($dept, $depts, true)) {
$errors[] = "第 {$i} 行:部门不存在";
continue;
}
if (!preg_match('/^\d{17}[\dXx]$/', $idcard)) {
$errors[] = "第 {$i} 行:身份证格式错误";
continue;
}
七、导入后处理:失败行导出
// 把校验失败的行写回一个 Excel,用户下载修正
if (!empty($errors)) {
$obj = new \PHPExcel();
$sheet = $obj->getActiveSheet();
$sheet->fromArray(['行号', '错误原因'], null, 'A1');
$r = 2;
foreach ($errors as $msg) {
$sheet->setCellValue('A' . $r, $r);
$sheet->setCellValue('B' . $r, $msg);
$r++;
}
$writer = \PHPExcel_IOFactory::createWriter($obj, 'Excel2007');
$writer->save(runtime_path() . 'import/errors.xlsx');
}
八、完整流程图
上传 → 扩展名/大小校验 → 移动临时目录
→ 读取工作表 → 表头校验
→ 逐行解析 → 字段校验(收集错误)
→ 批量 insertAll(事务)
→ 删除临时文件 → 返回成功数 + 错误明细