使用Python从企业SharePoint读取/下载Excel文件遇400错误求助
问题排查与解决方案
核心问题:Graph API 请求 URL 格式错误
400 错误源于请求格式不符合规范,你当前拼接的 Graph API URL 未遵循站点、驱动器与文件的层级结构要求。
具体修正步骤
修正 URL 格式
Microsoft Graph 访问 SharePoint 文件需按「站点→驱动器→文件」的层级构造请求:- Teams 关联的 SharePoint 站点标识应为
sites/myorganization.sharepoint.com:/teams/group: Shared Documents是站点默认文档库,对应驱动器根目录(/drive/root),因此文件路径只需保留folder1/folder2/folder3/myexcelfile.xlsx
正确的请求 URL:
graph_url = f'https://graph.microsoft.com/v1.0/sites/myorganization.sharepoint.com:/teams/group:/drive/root:/folder1/folder2/folder3/myexcelfile.xlsx:/content'- Teams 关联的 SharePoint 站点标识应为
添加错误详情排查
在请求失败时打印响应的错误详情,便于精准定位问题:else: print(f"Read file failed. Status code: {response.status_code}") if response.content: print("Error details:", response.json())确认权限配置
再次验证 Azure AD 应用的应用权限(非委托权限):- 需配置
Files.Read.All或Sites.Read.All - 已获取管理员同意授权
- 需配置
修正后的完整代码
import requests import msal import io import pandas as pd # Azure App Parameters client_id = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' client_secret = 'mysecrethere' authority = 'https://login.microsoftonline.com/tenant_id' # SharePoint Parameters sharepoint_site_url = 'https://myorganization.sharepoint.com' excel_file_relative_path = 'folder1/folder2/folder3/myexcelfile.xlsx' # Create a ConfidentialClientApplication instance for credentials app = msal.ConfidentialClientApplication(client_id, authority=authority, client_credential=client_secret) # Acquire an access token using client credentials result = app.acquire_token_silent(scopes=['https://graph.microsoft.com/.default'], account=None) print(result) if not result: result = app.acquire_token_for_client(scopes=['https://graph.microsoft.com/.default']) print(result) if 'access_token' in result: access_token = result['access_token'] # 修正后的Graph API请求URL graph_url = f'https://graph.microsoft.com/v1.0/sites/myorganization.sharepoint.com:/teams/group:/drive/root:/{excel_file_relative_path}:/content' headers = {'Authorization': f'Bearer {access_token}'} response = requests.get(graph_url, headers=headers) if response.status_code == 200: excel_data = io.BytesIO(response.content) df = pd.read_excel(excel_data) print(df.head()) else: print(f"Read file failed. Status code: {response.status_code}") if response.content: print("Error details:", response.json()) else: print("Failed to get access token.")
额外提示
若修正后仍报错,可通过错误详情进一步排查:
- 提示「权限不足」:检查应用权限是否正确配置并获得管理员同意
- 提示「文件不存在」:确认站点路径与文件相对路径是否准确
内容的提问来源于stack exchange,提问作者Tamara Dominguez Poncelas
相关产品推荐
相关产品推荐

