php实现excel导入数据库
PHP 实现 Excel 导入数据库
使用 PHPExcel 或 PhpSpreadsheet 库
PhpSpreadsheet 是 PHPExcel 的继承者,推荐使用 PhpSpreadsheet 来处理 Excel 文件。可以通过 Composer 安装:
composer require phpoffice/phpspreadsheet
读取 Excel 文件并将数据插入数据库的示例代码:
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\IOFactory;
// 数据库连接
$db = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
// 加载 Excel 文件
$spreadsheet = IOFactory::load('example.xlsx');
$worksheet = $spreadsheet->getActiveSheet();
// 遍历行
foreach ($worksheet->getRowIterator() as $row) {
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false);
$data = [];
foreach ($cellIterator as $cell) {
$data[] = $cell->getValue();
}
// 插入数据库
$stmt = $db->prepare("INSERT INTO table_name (col1, col2, col3) VALUES (?, ?, ?)");
$stmt->execute($data);
}
使用 Laravel Excel 包(Laravel 框架)
对于 Laravel 项目,可以使用 maatwebsite/excel 包:

composer require maatwebsite/excel
创建导入类:
namespace App\Imports;
use Maatwebsite\Excel\Concerns\ToModel;
class UsersImport implements ToModel
{
public function model(array $row)
{
return new User([
'name' => $row[0],
'email' => $row[1],
]);
}
}
在控制器中使用:

use App\Imports\UsersImport;
use Maatwebsite\Excel\Facades\Excel;
public function import()
{
Excel::import(new UsersImport, 'users.xlsx');
return redirect('/')->with('success', 'All good!');
}
使用 SimpleXLSX 库(轻量级方案)
对于简单的 Excel 文件,可以使用 SimpleXLSX:
require_once 'simplexlsx.class.php';
if ($xlsx = SimpleXLSX::parse('example.xlsx')) {
$db = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
foreach ($xlsx->rows() as $row) {
$stmt = $db->prepare("INSERT INTO table_name (col1, col2) VALUES (?, ?)");
$stmt->execute([$row[0], $row[1]]);
}
} else {
echo SimpleXLSX::parseError();
}
处理 CSV 文件
如果数据是 CSV 格式,可以直接使用 PHP 内置函数:
$file = fopen('data.csv', 'r');
$db = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
while (($row = fgetcsv($file)) !== false) {
$stmt = $db->prepare("INSERT INTO table_name (col1, col2) VALUES (?, ?)");
$stmt->execute([$row[0], $row[1]]);
}
fclose($file);
注意事项
- 验证数据格式和类型
- 处理可能的空值
- 考虑使用事务确保数据完整性
- 对于大文件,考虑分块处理
- 添加适当的错误处理机制
- 注意文件上传安全,验证文件类型和内容






