如何通过Google Sheets API获取单元格原始数据及Google Drive文件链接?
获取Google Sheets中Drive文件的原始链接
当你通过spreadsheets.get API仅获取到文件名(如test_file.kml)时,是因为默认返回的是单元格的显示值,而Drive文件的实际链接存储在单元格的hyperlink属性中。以下是解决方法:
1. 修改API请求参数
必须开启includeGridData=true以获取单元格的详细元数据,并通过fields参数指定要返回的hyperlink字段,避免返回冗余数据。
关键参数设置:
includeGridData设为truefields指定为spreadsheets/sheets(data(rowData(values(hyperlink,formattedValue))))
2. 解析返回结果
API响应中,目标单元格的hyperlink字段会直接包含对应的Google Drive文件链接(格式类似https://drive.google.com/open?id=XXX或https://docs.google.com/file/d/XXX/edit)。
Python示例代码
from googleapiclient.discovery import build # 初始化服务(需提前完成OAuth认证) service = build('sheets', 'v4', credentials=your_credentials) spreadsheet_id = "你的表格ID" target_range = "Sheet1!A1" # 替换为目标单元格范围 # 发送API请求 response = service.spreadsheets().get( spreadsheetId=spreadsheet_id, includeGridData=True, fields='sheets(data(rowData(values(hyperlink,formattedValue))))' ).execute() # 提取链接和显示值 cell_data = response['sheets'][0]['data'][0]['rowData'][0]['values'][0] print(f"显示文件名: {cell_data['formattedValue']}") print(f"Drive文件链接: {cell_data['hyperlink']}")
补充说明
如果单元格是通过富文本插入的链接(而非直接插入Drive文件),则需要解析richText.runs中的link.url字段,该字段同样包含目标链接。
内容的提问来源于stack exchange,提问作者IceCreamVan
相关产品推荐
相关产品推荐

