You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python office365库读取SharePoint Excel文件报错求助

解决使用Python office365库读取SharePoint Excel文件时的「File is not a recognized Excel file」错误

你当前遇到的问题核心是使用了错误的SharePoint文件URL,代码里的URL是SharePoint的文档预览页面(Doc.aspx)链接,而非文件的直接访问链接,导致File.open_binary获取的是网页内容而非Excel文件本身,所以pandas无法识别。

1. 获取正确的文件直接链接

在SharePoint中找到目标Excel文件:

  • 右键点击文件 → 选择「复制链接」
  • 在弹出窗口中,选择「直接链接」(部分版本可能显示为「复制直接链接」)
  • 复制的链接应该以.xlsx结尾,类似:https://company.sharepoint.com/sites/folder1/folder1/Shared%20Documents/excel%20file%20name.xlsx

2. 修正代码中的认证与URL逻辑

原代码中AuthenticationContext和ClientContext应传入SharePoint站点的根URL,而非文件或预览页面的URL,File.open_binary则使用文件的直接链接。修正后的代码如下:

from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.files.file import File 
import io
import pandas as pd

# SharePoint站点根URL
site_url = 'https://company.sharepoint.com/sites/folder1/folder1'
# 文件的直接访问URL
file_url = 'https://company.sharepoint.com/sites/folder1/folder1/Shared%20Documents/excel%20file%20name.xlsx'
username = 'user.name@company.com'
password = 'password'

ctx_auth = AuthenticationContext(site_url)
if ctx_auth.acquire_token_for_user(username, password):
    ctx = ClientContext(site_url, ctx_auth)
    web = ctx.web
    ctx.load(web)
    ctx.execute_query()
    print("Authentication successful")
else:
    print(f"Authentication failed: {ctx_auth.get_last_error()}")
    exit()

# 获取文件二进制内容
response = File.open_binary(ctx, file_url)

bytes_file_obj = io.BytesIO(response.content)
bytes_file_obj.seek(0) 
df = pd.read_excel(bytes_file_obj)
print(df.head())

额外注意事项

  • 若账号开启多因素认证(MFA),直接使用密码会认证失败,需使用微软账户设置中生成的应用密码,或改用证书认证、Azure AD应用权限认证等方式。
  • 确保你拥有目标文件的读取权限,权限不足时execute_query()会抛出相关异常。

内容的提问来源于stack exchange,提问作者Smbat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 23:42:46