使用Python读取SharePoint中Excel文件时返回'Invalid Request'错误
背景
- 本地已基于Pandas读取、xlWings写入完成Excel文件读写方案,现需迁移至SharePoint供多用户访问
- 目标Excel用于物品位置追踪,无计算逻辑,需读取A1:V20区域,该区域存在大量空单元格
- 已完成Microsoft Graph身份验证,应用已配置对应权限,但调用API始终无法获取预期结果
遇到的错误
- 最初使用以
/workbook/tables('Plant_3')结尾的URL时,收到错误:
{ "error": { "code": "BadRequest", "message": "Open navigation properties are not supported on OpenTypes. Property name: 'tables'." } }
推测原因:目标Excel未创建表格对象,URL尝试访问不存在的表格资源导致。
- 更新URL后,收到新错误:
{ "error": { "code": "invalidRequest", "message": "Invalid request" } }
同时控制台输出'value',说明解析响应时未找到对应字段。
当前代码
from msal import ConfidentialClientApplication import requests import json import pandas as pd import configparser config = configparser.ConfigParser() config.read('config.ini') client_id = config['entra_auth']['client_id'] client_secret = config['entra_auth']['client_secret'] tenant_id = config['entra_auth']['tenant_id'] msal_scope = ['https://graph.microsoft.com/.default'] msal_app = ConfidentialClientApplication(client_id=client_id, authority=f"https://login.microsoftonline.com/{tenant_id}", client_credential=client_secret, ) result = msal_app.acquire_token_silent(scopes=msal_scope, account=None) if not result: result = msal_app.acquire_token_for_client(scopes=msal_scope) if 'access_token' in result: access_token = result['access_token'] else: raise Exception("Failed to acquire token") headers = {'Authorization': f'Bearer {access_token}'} site_id = config['site']['site_id'] document_library_id = config['site']['document_library_id'] doc_id = config['site']['doc_id'] # 构造请求URL url = f"https://graph.microsoft.com/v1.0/sites/{site_id}/drives/{document_library_id}/items/{doc_id}:/workbook/worksheets('Plant_3')/range(address='A1:V20')" # 请求API并尝试解析为DataFrame response = requests.get(url, headers=headers) try: data = response.json().get("value", []) if data: df = pd.DataFrame(data) print(df) else: print("No data") except Exception as e: print(f"Error: {e}")
内容的提问来源于stack exchange,提问作者Python_Learner
相关产品推荐
相关产品推荐

