如何通过Google API读取Google Sheets数据并保存至Laravel数据库
Laravel 读取Google Sheets数据并导入数据库详细步骤
1. 准备Google Cloud服务账号与权限
- 登录Google Cloud控制台,创建新项目(或使用现有项目)
- 搜索并启用Google Sheets API
- 进入「IAM与管理」→「服务账号」,创建新服务账号,填写名称和邮箱
- 为服务账号添加「Editor」权限(或更细的Sheets访问权限)
- 点击服务账号→「密钥」→「添加密钥」→「创建新密钥」,选择JSON格式,下载密钥文件
- 将密钥文件放到Laravel项目的
storage/app目录下,重命名为google-service-account.json(方便后续引用) - 打开你的Google Sheets,点击「共享」,将服务账号的邮箱(格式类似
xxx@xxx.iam.gserviceaccount.com)添加为协作者,授予「编辑」权限
2. 安装Google API客户端包
在Laravel项目根目录执行Composer命令:
composer require google/apiclient:^2.0
3. 添加配置项
- 在
.env文件中添加以下配置:
GOOGLE_SERVICE_ACCOUNT_PATH=storage/app/google-service-account.json GOOGLE_SHEET_ID=你的Google Sheets文档ID(从URL中获取,示例:https://docs.google.com/spreadsheets/d/[此处为ID]/...) GOOGLE_SHEET_RANGE=Sheet1!A2:Z # 跳过表头,读取从第二行开始的数据
- 可选:创建
config/google.php配置文件统一管理配置:
<?php return [ 'service_account_path' => env('GOOGLE_SERVICE_ACCOUNT_PATH'), 'sheet_id' => env('GOOGLE_SHEET_ID'), 'sheet_range' => env('GOOGLE_SHEET_RANGE'), ];
4. 创建数据库模型与迁移
假设我们要导入商品数据,创建模型和迁移:
php artisan make:model Product -m
- 编辑迁移文件
database/migrations/xxxx_xx_xx_xxxxxx_create_products_table.php,定义对应Sheets列的字段:
public function up() { Schema::create('products', function (Blueprint $table) { $table->id(); $table->string('name'); // 对应Sheets A列商品名 $table->decimal('price', 8, 2); // 对应B列价格 $table->text('description')->nullable(); // 对应C列描述 $table->timestamps(); }); }
- 执行迁移:
php artisan migrate
5. 创建Artisan命令实现数据导入
创建自定义命令:
php artisan make:command ImportSheetsData
- 编辑
app/Console/Commands/ImportSheetsData.php:
<?php namespace App\Console\Commands; use Illuminate\Console\Command; use Google\Client; use Google\Service\Sheets; use App\Models\Product; class ImportSheetsData extends Command { protected $signature = 'sheets:import'; protected $description = 'Import data from Google Sheets to database'; public function handle() { // 初始化Google客户端 $client = new Client(); $client->setApplicationName('Laravel Sheets Import'); $client->setScopes(Sheets::SPREADSHEETS_READONLY); $client->setAuthConfig(config('google.service_account_path')); $client->setAccessType('offline'); // 创建Sheets服务实例 $service = new Sheets($client); // 读取Sheets数据 $response = $service->spreadsheets_values->get( config('google.sheet_id'), config('google.sheet_range') ); $values = $response->getValues(); if (empty($values)) { $this->info('No data found in the sheet.'); return; } // 批量插入/更新数据 foreach ($values as $row) { // 索引对应Sheets列,根据实际结构调整 $productData = [ 'name' => $row[0] ?? '', 'price' => isset($row[1]) ? (float)$row[1] : 0, 'description' => $row[2] ?? null, ]; // 使用updateOrCreate避免重复导入 Product::updateOrCreate( ['name' => $productData['name']], // 唯一标识字段,按需调整 $productData ); } $this->info('Successfully imported ' . count($values) . ' records!'); } }
6. 执行数据导入
在项目根目录执行命令:
php artisan sheets:import
执行完成后会提示导入成功的记录数,可查看数据库products表确认数据是否导入。
常见问题排查
- 权限错误:确认服务账号邮箱已添加到Sheets共享且有编辑权限;密钥文件路径正确,Laravel有读取权限
- 数据为空:检查
GOOGLE_SHEET_RANGE是否匹配Sheet名称,数据是否在指定范围内 - 数据类型错误:确保Sheets中数据格式与数据库字段类型匹配(如价格列需为数字格式)
- 依赖问题:包安装失败时,尝试清除Composer缓存:
composer clear-cache后重新安装
内容的提问来源于stack exchange,提问作者Ankit Raj
相关产品推荐
相关产品推荐

