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

如何使用Python读取并提取SharePoint中Excel文件的数据

问题根因

你当前只是定义了relative_url这个字符串变量,执行变量自然只会输出字符串本身,你没有完成SharePoint身份认证、文件内容拉取、以及把远程文件内容传给Excel处理库的完整流程,所以拿不到实际数据。

修复步骤
  • 第一步:完成SharePoint身份认证,拉取Excel文件的二进制内容到内存,再通过openpyxl直接读取(无需保存本地)
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 openpyxl

# 替换为你实际的SharePoint配置信息
site_url = 'https://yoursharepointsite.com/sites/documentsite'
username = 'yourusername'
password = 'yourpassword'
file_relative_url = '/sites/documentsite/Documents/filename.xlsx'

# 鉴权逻辑
ctx_auth = AuthenticationContext(site_url)
if ctx_auth.acquire_token_for_user(username, password):
    ctx = ClientContext(site_url, ctx_auth)
    # 拉取文件二进制内容
    response = File.open_binary(ctx, file_relative_url)
    # 转为内存字节流供openpyxl读取
    excel_stream = io.BytesIO(response.content)
    # 读取Excel内容,可直接做后续数据处理
    wb = openpyxl.load_workbook(excel_stream)
    # 测试:打印第一个工作表的最大行、最大列数
    active_sheet = wb.active
    print(f"工作表行数:{active_sheet.max_row}, 列数:{active_sheet.max_column}")
else:
    print("鉴权失败:", ctx_auth.get_last_error())
  • 第二步:如果你必须使用xlwings处理文件,需要先把拉取到的内容存为本地临时文件再调用,xlwings本身不支持直接读取内存流数据
import xlwings as xw
import tempfile
import os

# 接上述拉取到response.content的步骤
# 生成临时Excel文件
with tempfile.NamedTemporaryFile(suffix='.xlsx', delete=False) as tmp_file:
    tmp_file.write(response.content)
    tmp_path = tmp_file.name

# 用xlwings打开临时文件
wb = xw.Book(tmp_path)
# 你的业务处理逻辑写在这里

# 处理完成后删除临时文件(不需要保留本地副本的情况下执行)
os.remove(tmp_path)
常见注意事项
  • 如果你的SharePoint开启了多因素认证(MFA),不能直接用账号密码鉴权,需要替换为应用注册的client id、client secret方式鉴权
  • xlwings依赖本地安装的Office程序,运行环境必须安装对应版本的Excel才能正常使用
  • 注意文件相对路径要从站点根目录开始计算,不要包含SharePoint域名部分,避免路径写错导致拉取文件失败

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 20:06:02