> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# Google Sheets API for Laravel

> 在 Laravel 中使用 Google Sheets API v4。提供流畅、直观的接口。

一个面向 Laravel 的 Google Sheets API v4 扩展包。它屏蔽了 Google PHP 客户端库的复杂性，提供了直观且富有表现力的方法链 API。

## 特性

* **支持多种认证方式** —— OAuth 2.0（面向单个用户的访问）、Service Account（服务器间通信）、API key（公开数据）
* **流畅的 API** —— 通过方法链直观地操作数据
* **与 Laravel Collection 集成** —— 将 Google Sheets 的数据转换为 Laravel Collection，方便进行数组处理
* **可扩展** —— 通过 macro 系统可以为 facade 添加自定义方法
* **与 Google Drive 集成** —— 支持电子表格的管理与列表查询

## 常见使用场景

* **用户仪表盘** —— 展示与操作 Google Sheets 中的数据
* **数据导入 / 导出** —— 在 Laravel 应用与 Google Sheets 之间迁移大量数据
* **自动生成报表** —— 通过程序生成和更新报表
* **多用户应用** —— 让用户各自管理自己的 Google Sheets

## 设计理念

本包的主要目的是 **从 Google Sheets 读取数据**。它并不鼓励在读取前指定复杂条件，而是先将全部数据取回作为 Laravel Collection，然后在 Laravel 一侧进行后续处理。

## 系统要求

* PHP >= 8.3
* Laravel >= 12.0

## 安装

<Steps>
  <Step title="用 Composer 安装">
    ```bash theme={null}
    composer require revolution/laravel-google-sheets
    ```
  </Step>

  <Step title="发布配置文件">
    ```bash theme={null}
    php artisan vendor:publish --tag="google-config"
    ```
  </Step>

  <Step title="启用 Google API">
    在 [Google Cloud Console](https://console.cloud.google.com/) 中启用以下 API：

    * **Google Sheets API**
    * **Google Drive API**
  </Step>

  <Step title="选择并配置认证方式">
    从下列三种方式中选择：

    * [Service Account](/zh/packages/laravel-google-sheets/service-account) —— 面向服务器间通信 / 自动化任务
    * [OAuth 2.0](/zh/packages/laravel-google-sheets/oauth) —— 面向单个用户的访问
    * API key —— 仅公开数据
  </Step>
</Steps>

## 认证方式对比

| 方式                  | 用途           | 用户操作 | 访问范围       | 难度 |
| ------------------- | ------------ | ---- | ---------- | -- |
| **Service Account** | 服务器间通信 / 自动化 | 不需要  | 已共享的电子表格   | 中  |
| **OAuth 2.0**       | 面向用户的应用      | 需要同意 | 用户各自的表格    | 高  |
| **API key**         | 仅公开数据        | 不需要  | 只能访问公开电子表格 | 低  |

## 基本用法

以下面的电子表格结构为例。

| id | name  | mail  |
| -- | ----- | ----- |
| 1  | name1 | mail1 |
| 2  | name2 | mail2 |

电子表格 URL: `https://docs.google.com/spreadsheets/d/{spreadsheetID}/...`

请从 URL 中取出 `spreadsheetId`。

### 使用 Service Account

使用 Service Account 认证时，不需要额外设置 token。

```php theme={null}
use Revolution\Google\Sheets\Facades\Sheets;

// Service Account 认证会在初始化时自动完成
$values = Sheets::spreadsheet('spreadsheetId')->sheet('Sheet 1')->all();
// [
//   ['id', 'name', 'mail'],
//   ['1', 'name1', 'mail1'],
//   ['2', 'name2', 'mail2']
// ]
```

### 使用 OAuth

使用 OAuth 认证时，需要设置用户的 access token。

```php theme={null}
use Revolution\Google\Sheets\Facades\Sheets;

$user = $request->user();

$token = [
    'access_token'  => $user->access_token,
    'refresh_token' => $user->refresh_token,
    'expires_in'    => $user->expires_in,
    'created'       => $user->updated_at->getTimestamp(),
];

// all() 返回数组
$values = Sheets::setAccessToken($token)->spreadsheet('spreadsheetId')->sheet('Sheet 1')->all();
// [
//   ['id', 'name', 'mail'],
//   ['1', 'name1', 'mail1'],
//   ['2', 'name1', 'mail2']
// ]
```

### 用表头作为 key 获取数据（推荐）

Collection 的转换比较方便，后续处理也更灵活，因此推荐这种方式。

```php theme={null}
use Revolution\Google\Sheets\Facades\Sheets;

// get() 返回 Laravel Collection
$rows = Sheets::sheet('Sheet 1')->get();

$header = $rows->pull(0);
$values = Sheets::collection(header: $header, rows: $rows);
$values->toArray()
// [
//   ['id' => '1', 'name' => 'name1', 'mail' => 'mail1'],
//   ['id' => '2', 'name' => 'name2', 'mail' => 'mail2']
// ]
```

Blade

```php theme={null}
@foreach($values as $value)
  {{ data_get($value, 'name') }}
@endforeach
```

### 使用 A1 表示法

```php theme={null}
use Revolution\Google\Sheets\Facades\Sheets;

$values = Sheets::sheet('Sheet 1')->range('A1:B2')->all();
// [
//   ['id', 'name'],
//   ['1', 'name1'],
// ]
```

### 关于 A1 表示法

A1 表示法是 Google 电子表格中指定单元格或范围的标准方式（例如 “A1”、“A1:B2”）。

* “A1” 指的是 A 列第 1 行的单元格。
* “A1:B2” 指的是从 A1 到 B2 的矩形范围。
* “A:B” 指的是 A 列和 B 列的全部行。

如果你对 A1 表示法不太熟悉，或者范围是动态的、比较复杂，通常先获取全部数据、再在 Laravel 中通过 Collection 处理/过滤，会更简单。

## 后续步骤

* [Service Account 认证](/zh/packages/laravel-google-sheets/service-account) —— 最常见的方式
* [OAuth 2.0 认证](/zh/packages/laravel-google-sheets/oauth) —— 面向单个用户的访问
* [laravel-google-sheets](https://github.com/invokable/laravel-google-sheets)
* [示例项目](https://github.com/invokable/google-sheets-project) —— 覆盖 Laravel 5.5 到 13 的示例
* [相关包: Google Search Console API for Laravel](https://github.com/invokable/laravel-google-searchconsole)

## 在线演示

你可以通过 [Laravel Google Sheets Demo](https://sheets.kawax.biz/) 查看实际运行效果。


## Related topics

- [Google Sheets API for Laravel](/it/packages/laravel-google-sheets/index.md)
