gspread

1
pip install gspread
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import gspread
from google.oauth2.service_account import Credentials

#认证
#必须用scopes
scopes = [
"https://www.googleapis.com/auth/spreadsheets",
"https://www.googleapis.com/auth/drive"
]
creds = Credentials.from_service_account_file('xxx.json', scopes=scopes)

client = gspread.authorize(creds)

#open google sheet
sheet_url = 'https://docs.google.com/spreadsheets/d/xxx.com'
sh = client.open_by_url(sheet_url)

#选择工作表

worksheet = sh.sheet1 #默认第一个工作表

worksheet1 = sh.worksheet("工作表1") #选择工作表



#write data

worksheet.update('A1', [["Hello gspread"]])
worksheet.update('A2', [['2026-01-22']])


#批量写入
data = [
['name', 'age', 'city'],
['steve', 18, 'Las Vegas'],
['alice', 20, 'New York']
]

worksheet.update('A2', data)


# read data

values = worksheet.get_all_values()
print("data: ")
for row in values:
print(row)

#单个单元格更新
worksheet.update_acell('B3', 30)