Python 如何使用Python访问(读取、写入)Google Sheets电子表格

Python 如何使用Python访问(读取、写入)Google Sheets电子表格

在本文中,我们将介绍如何使用Python访问(读取、写入)Google Sheets电子表格。通过使用Google Sheets API和Python的相关库,我们可以轻松地与Google Sheets进行交互,实现数据的读取和写入。

阅读更多:Python 教程

准备工作

在开始之前,我们需要完成以下准备工作:
1. 创建一个Google Cloud项目并启用Google Sheets API。
2. 生成一个API密钥,以便将其用于身份验证。

安装依赖库

首先,我们需要安装两个Python库:gspreadoauth2client。在命令行中运行以下命令来安装它们:

pip install gspread oauth2client
Python

读取Google Sheets电子表格数据

我们将从访问(读取)Google Sheets电子表格开始。

步骤1:导入库和凭据

首先,导入所需的库和凭据。您可以将凭据存储在一个文件中,例如credentials.json,然后使用以下代码导入:

import gspread
from oauth2client.service_account import ServiceAccountCredentials

# 导入凭据
credentials = ServiceAccountCredentials.from_json_keyfile_name('credentials.json', ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive'])

# 授权凭据
gc = gspread.authorize(credentials)
Python

步骤2:打开电子表格

接下来,使用以下代码打开电子表格:

# 打开电子表格
sheet = gc.open('电子表格名称').sheet1
Python

电子表格名称替换为您要访问的实际电子表格的名称。

步骤3:读取数据

现在,我们可以使用以下代码获取电子表格的数据:

# 读取数据
data = sheet.get_all_records()
Python

此代码将返回一个包含电子表格中所有行数据的列表。

示例

下面是一个完整的示例,它将输出电子表格中的所有行数据:

import gspread
from oauth2client.service_account import ServiceAccountCredentials

# 导入凭据
credentials = ServiceAccountCredentials.from_json_keyfile_name('credentials.json', ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive'])

# 授权凭据
gc = gspread.authorize(credentials)

# 打开电子表格
sheet = gc.open('电子表格名称').sheet1

# 读取数据
data = sheet.get_all_records()

# 输出数据
for row in data:
    print(row)
Python

写入数据到Google Sheets电子表格

接下来,我们将学习如何使用Python将数据写入Google Sheets电子表格。

步骤1:导入库和凭据

首先,与读取数据一样,我们需要导入库和凭据。使用以下代码导入凭据:

import gspread
from oauth2client.service_account import ServiceAccountCredentials

# 导入凭据
credentials = ServiceAccountCredentials.from_json_keyfile_name('credentials.json', ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive'])

# 授权凭据
gc = gspread.authorize(credentials)
Python

步骤2:打开电子表格

然后,使用以下代码打开电子表格:

# 打开电子表格
sheet = gc.open('电子表格名称').sheet1
Python

电子表格名称替换为您要访问的实际电子表格的名称。

步骤3:写入数据

使用以下代码将数据写入电子表格:

# 写入数据
data = [['John', 'Doe', 25], ['Jane', 'Smith', 30]]
sheet.insert_rows(data, 2)
Python

此代码将在第二行插入一个包含姓名和年龄的数据。

示例

下面是一个完整的示例,它将向电子表格写入数据:

import gspread
from oauth2client.service_account import ServiceAccountCredentials

# 导入凭据
credentials = ServiceAccountCredentials.from_json_keyfile_name('credentials.json', ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive'])

# 授权凭据
gc = gspread.authorize(credentials)

# 打开电子表格
sheet = gc.open('电子表格名称').sheet1

# 写入数据
data = [['John', 'Doe', 25], ['Jane', 'Smith', 30]]
sheet.insert_rows(data, 2)
Python

总结

通过Google Sheets API和Python的相关库,我们可以轻松地访问(读取、写入)Google Sheets电子表格。我们可以使用gspreadoauth2client库与Google Sheets API进行交互,并通过简单的代码实现数据的读取和写入。希望本文对您有所帮助!

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册