1
我有一個表格,它以Python列表的形式列出,我想用gspread
庫將其寫入一些Google Spreadsheet。但是,gspread
似乎沒有這種功能。當然,我可以使用循環和更新特定的單元格,但這是非常低效的解決方案,因爲它必須執行多個請求(每個單元一個請求)。如何做得更好?如何使用gspread將表格(列表清單)寫入Google電子表格
我有一個表格,它以Python列表的形式列出,我想用gspread
庫將其寫入一些Google Spreadsheet。但是,gspread
似乎沒有這種功能。當然,我可以使用循環和更新特定的單元格,但這是非常低效的解決方案,因爲它必須執行多個請求(每個單元一個請求)。如何做得更好?如何使用gspread將表格(列表清單)寫入Google電子表格
您可以使用Worksheet.range
來選擇想要更新的範圍,然後將表格內容寫入此範圍並使用Worksheet.update_cells
批量更新它們。
下面的代碼片段修改自this tutorial。
def numberToLetters(q):
"""
Helper function to convert number of column to its index, like 10 -> 'A'
"""
q = q - 1
result = ''
while q >= 0:
remain = q % 26
result = chr(remain+65) + result;
q = q//26 - 1
return result
def colrow_to_A1(col, row):
return numberToLetters(col)+str(row)
def update_sheet(ws, rows, left=1, top=1):
"""
updates the google spreadsheet with given table
- ws is gspread.models.Worksheet object
- rows is a table (list of lists)
- left is the number of the first column in the target document (beginning with 1)
- top is the number of first row in the target document (beginning with 1)
"""
# number of rows and columns
num_lines, num_columns = len(rows), len(rows[0])
# selection of the range that will be updated
cell_list = ws.range(
colrow_to_A1(left,top)+':'+colrow_to_A1(left+num_columns-1, top+num_lines-1)
)
# modifying the values in the range
for cell in cell_list:
val = rows[cell.row-top][cell.col-left]
cell.value = val
# update in batch
ws.update_cells(cell_list)
您可以通過以下方式來使用它:
import gspread
from oauth2client.service_account import ServiceAccountCredentials
# your auth here
scope = ['https://spreadsheets.google.com/feeds']
credentials = ServiceAccountCredentials.from_json_keyfile_name('credentials.json', scope)
gc = gspread.authorize(credentials)
# your spreadsheet have to be shared with 'client_email' from credentials.json
gc = gspread.authorize(credentials)
# end of auth
spreadsheet = gc.open_by_url(my_url) # url to your spreadsheet here
ws = spreadsheet.sheet1 # or select any other sheet
table = [['one', 'two', 'three'], [4, 5, 6]]
# you may need to resize your worksheet so it have the neccessary cells
# ws.resize(len(table),len(table[0]))
update_sheet(ws, table)