检查 Google 工作表中的单元格是否插入了超链接

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

我希望我的代码检查列中的单元格值并仅选择包含超链接的行。函数 has_hyperlink 适用于本地存储的 Excel 文件,但是当我尝试在 google 工作表上使用它时,出现错误 AttributeError: 'Cell' object has no attribute 'hyperlink'。这是我使用的代码,这里是谷歌表格的链接spreadsheet。谢谢您的帮助!

import gspread
from oauth2client.service_account import ServiceAccountCredentials

def has_hyperlink(cell):
    """
    Check if a cell has a hyperlink.
    """
    if 'hyperlink' in cell:
        return True
    return False

# Set up credentials
scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
credentials = ServiceAccountCredentials.from_json_keyfile_name('path/to/your/credentials.json', scope)
gc = gspread.authorize(credentials)

# Open the Google Sheet by title
spreadsheet = gc.open('Your Google Sheet Title')

# Select the worksheet (e.g., the first sheet)
worksheet = spreadsheet.sheet1

# Specify the cell you want to check (e.g., B2)
cell_to_check = worksheet.cell(2, 2)

# Check if the cell has a hyperlink
if has_hyperlink(cell_to_check._properties):
    print(f"The cell B2 has a hyperlink: {cell_to_check.hyperlink}")
else:
    print("The cell B2 does not have a hyperlink")

如果您可以帮助我检查超链接,那就太好了。谢谢!

python google-sheets google-sheets-api gspread
1个回答
1
投票

我相信您的目标如下。

  • 您想使用 Python 的 gspread 检查单元格是否具有超链接。

在你的脚本中,做如下修改怎么样?

修改后的脚本:

import gspread
from oauth2client.service_account import ServiceAccountCredentials
from googleapiclient.discovery import build


def has_hyperlink(obj, cell):
    """
    Check if a cell has a hyperlink.
    """
    r, c = gspread.utils.a1_to_rowcol(cell)
    o = obj["sheets"][0]["data"][0]["rowData"][r - 1].get("values", [])[c - 1]
    if 'hyperlink' in o:
        return True
    return False


scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
credentials = ServiceAccountCredentials.from_json_keyfile_name('path/to/your/credentials.json', scope)
gc = gspread.authorize(credentials)

spreadsheet = gc.open('Your Google Sheet Title')
worksheet = spreadsheet.sheet1

service = build("sheets", "v4", credentials=gc.auth)
obj = service.spreadsheets().get(spreadsheetId=spreadsheet.id, fields="sheets(data(rowData(values(hyperlink,formattedValue))))", ranges=[worksheet.title]).execute()

cell1 = "A2"
res1 = has_hyperlink(obj, cell1)
print(res1)

cell2 = "B2"
res2 = has_hyperlink(obj, cell2)
print(res2)
  • 在此修改中,使用方法:spreadsheets.get检查超链接。为了使用此方法,需要将 google-api-python-client 与 gspread 客户端一起使用。

  • 当此脚本运行到您提供的电子表格时,

    True
    False
    将显示为输出值。

参考:

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