gspread python 格式化问题

问题描述 投票:0回答:1

worksheet.clear() 不会清除单元格上的格式,它只是清除值是否有办法清除所有单元格或指定范围上的格式

我尝试过 cellformat 粗体无并将其传递给 gspread 的格式函数,但它不起作用 这是我尝试过的代码

if len(list_of_lists) != 0:
    num_rows = len(list_of_lists)
    num_cols = len(list_of_lists[0]) if num_rows > 0 else 0
    start_cell = 'A1'
    end_cell = gspread.utils.rowcol_to_a1(num_rows, num_cols)
    print("start cell",start_cell,"end cell:", end_cell)
    data_range = f"{start_cell}:{end_cell}"
    print("data range",data_range)
    clear_format = cellFormat(
    backgroundColor=None,  # Clear background color
    textFormat=textFormat(bold=False, foregroundColor=None),  # Reset text format
    horizontalAlignment=None  # Reset horizontal alignment
    )
    format_cell_range(worksheet, data_range, clear_format) 
    worksheet.clear()
    print("Formatting cleared")
    cleared = True
python gspread
1个回答
0
投票

虽然我不确定是否能正确理解你的预期结果,但是下面的修改怎么样?

修改后的脚本:

来自

if len(list_of_lists) != 0:
    num_rows = len(list_of_lists)
    num_cols = len(list_of_lists[0]) if num_rows > 0 else 0
    start_cell = 'A1'
    end_cell = gspread.utils.rowcol_to_a1(num_rows, num_cols)
    print("start cell",start_cell,"end cell:", end_cell)
    data_range = f"{start_cell}:{end_cell}"
    print("data range",data_range)
    clear_format = cellFormat(
    backgroundColor=None,  # Clear background color
    textFormat=textFormat(bold=False, foregroundColor=None),  # Reset text format
    horizontalAlignment=None  # Reset horizontal alignment
    )
    format_cell_range(worksheet, data_range, clear_format) 
    worksheet.clear()
    print("Formatting cleared")
    cleared = True

致:

if len(list_of_lists) != 0:
    num_rows = len(list_of_lists)
    num_cols = len(list_of_lists[0]) if num_rows > 0 else 0
    start_cell = 'A1'
    end_cell = gspread.utils.rowcol_to_a1(num_rows, num_cols)
    print("start cell",start_cell,"end cell:", end_cell)
    data_range = f"{start_cell}:{end_cell}"
    print("data range",data_range)

    requests = [
        {
            "repeatCell": {
                "range": {"sheetId": worksheet.id, "startRowIndex": 0, "endRowIndex": num_rows, "startColumnIndex": 0, "endColumnIndex": num_cols},
                "fields": "*"
            }
        }
    ]
    worksheet.spreadsheet.batch_update({"requests": requests})

    worksheet.clear()
    print("Formatting cleared")
    cleared = True
  • 运行此修改后的脚本时,

    data_range
    的单元格值和格式将被清除。

  • 我看不到你的整个脚本。因此,我使用

    worksheet.spreadsheet
    作为 Spreadsheet 类对象。如果你已经声明为
    spreadsheet
    ,你也可以使用它。

注:

  • 如果要清除sheet中的所有单元格,请修改上述修改脚本中的

    requests
    ,如下所示。

    requests = [
        {
            "repeatCell": {
                "range": {"sheetId": worksheet.id},
                "fields": "*"
            }
        }
    ]
    

参考资料:

© www.soinside.com 2019 - 2024. All rights reserved.