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

使用Python读取SharePoint Online Excel文件时遇BadZipFile错误求助

解决SharePoint Excel读取BadZipFile错误

错误根源

你的代码存在两个关键问题:

  1. 未定义response变量,没有正确从SharePoint获取Excel文件的二进制数据,写入BytesIO的内容是无效的,导致pandas解析时识别为非zip格式文件(xlsx本质是zip包)
  2. 直接使用的url可能是SharePoint文件的网页预览地址,而非文件的二进制下载地址

修复方案

要直接在线读取SharePoint上的Excel文件,需通过Office365 API正确获取文件的二进制流,步骤如下:

  • 认证成功后,通过文件的服务器相对路径定位到目标文件
  • 使用File.open_binary()方法获取文件的二进制内容
  • 将二进制内容写入BytesIO后,再用pandas读取

完整修复代码

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

# 配置信息
site_url = "https://你的sharepoint站点根地址"  # 示例:https://xxx.sharepoint.com/sites/MyTeamSite
file_server_relative_url = "/sites/MyTeamSite/Shared Documents/目标文件.xlsx"  # 文件的服务器相对路径
username = "你的工作邮箱"
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')

    # 获取文件二进制内容
    file = ctx.web.get_file_by_server_relative_url(file_server_relative_url)
    file_content = file.open_binary(ctx).content

    # 写入BytesIO并读取为DataFrame
    bytes_file_obj = io.BytesIO(file_content)
    df = pd.read_excel(bytes_file_obj, engine='openpyxl')
    print(df)
else:
    print(f"Authentication failed: {ctx_auth.get_last_error()}")

注意事项

  • site_url是SharePoint站点的根地址,不是单个文件的网页预览地址
  • file_server_relative_url可通过右键SharePoint文件→复制直接链接,提取其中以/sites/开头的路径部分
  • 确保已安装依赖:pip install office365-rest-python-client pandas openpyxl

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 19:32:42