简体   繁体   English

使用 gspread,尝试在已存在的 Google 表格末尾添加一列

[英]Using gspread, trying to add a column at the end of Google Sheet that already exists

Here is the code I am working with.这是我正在使用的代码。

dfs=dfs[['Reserved']] #the column that I need to insert
dfs=dfs.applymap(str)    #json did not accept the nan so needed to convert
sh=gc.open_by_key('KEY')     #would open the google sheet 
sh_dfs=sh.get_worksheet(0)    #getting the worksheet
sh_dfs.insert_rows(dfs.values.tolist())    #inserts the dfs into the new worksheet

Running this code would insert the rows at the first column of the worksheet but what I am trying to accomplish is adding/inserting the column at the very last, column p.运行此代码将在工作表的第一列插入行,但我想要完成的是在最后一个列 p 处添加/插入列。

In your situation, how about the following modification?在您的情况下,如何进行以下修改? In this modification, at first, the maximum column is retrieved.在此修改中,首先检索最大值列。 And, the column number is converted to the column letter, and the values are put to the next column of the last column.并且,将列号转换为列字母,并将值放入最后一列的下一列。

From:从:

sh_dfs.insert_rows(dfs.values.tolist())

To:至:

# Ref: https://stackoverflow.com/a/23862195
def colnum_string(n):
    string = ""
    while n > 0:
        n, remainder = divmod(n - 1, 26)
        string = chr(65 + remainder) + string
    return string

values = sh_dfs.get_all_values()
col = colnum_string(max([len(r) for r in values]) + 1)
sh_dfs.update(col + '1', dfs.values.tolist(), value_input_option='USER_ENTERED')

Note:笔记:

  • If an error like exceeds grid limits occurs, please insert the blank column.如果出现exceeds grid limits等错误,请插入空白列。

Reference:参考:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM