如何使用gspread的append_row方法将内容追加到指定列?
解决gspread append_row写入指定列的问题
方法1:用空字符串占位
append_row默认会从每行的第一列开始填充,如果你要写入第N列,只需要在列表前面补充N-1个空字符串占位即可。比如要写入第3列,代码修改如下:
from oauth2client.service_account import ServiceAccountCredentials import gspread scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/drive.file', 'https://www.googleapis.com/auth/spreadsheets'] creds = ServiceAccountCredentials.from_json_keyfile_name('creds.json', scope) client = gspread.authorize(creds) sheet = client.open_by_url("url_to_spreadsheet").worksheet("Sheet1") # 写入第3列,前面加两个空字符串占位 sheet.append_row(["", "", "some text"])
这种方法适合需要一次性写入多列数据,同时指定某几列内容的场景。
方法2:直接定位行和列写入
如果只需要给指定列追加单个内容,可以先找到表格的下一个空行,再用update_cell直接写入目标列:
from oauth2client.service_account import ServiceAccountCredentials import gspread scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/drive.file', 'https://www.googleapis.com/auth/spreadsheets'] creds = ServiceAccountCredentials.from_json_keyfile_name('creds.json', scope) client = gspread.authorize(creds) sheet = client.open_by_url("url_to_spreadsheet").worksheet("Sheet1") # 获取当前已使用的最后一行,+1得到下一个空行 last_row = len(sheet.get_all_values()) + 1 # 指定要写入的列(比如第3列) target_col = 3 # 直接写入目标单元格 sheet.update_cell(last_row, target_col, "some text")
这种方法不需要填充空字符串,更适合单个单元格的追加场景。
内容的提问来源于stack exchange,提问作者theSlender
相关产品推荐
相关产品推荐

