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

将Pandas DataFrame保存至SharePoint Excel文件时遇导入错误

问题原因与解决办法

你遇到的ImportError不是缺少第三方包,而是tests模块是Office365-REST-Python-Client项目内部的测试专用模块——它只存在于项目源码仓库中,并非可通过pip安装的公开包,里面的test_user_credentials和test_team_site_url只是测试用的示例变量,直接导入必然报错。

解决步骤

  1. 删除错误导入语句:删掉from tests import test_user_credentials, test_team_site_url这一行。
  2. 导入正确凭证类:根据你的认证方式导入对应凭证类,普通账号密码认证用UserCredential。
  3. 替换为实际信息:将测试变量换成你自己的SharePoint站点地址、Office365账号信息。

修改后的完整代码

import os
from io import BytesIO
import pandas as pd  # 需导入pandas,且确保df已定义

from office365.sharepoint.client_context import ClientContext
from office365.runtime.auth.user_credential import UserCredential

# 替换为你的SharePoint站点URL
site_url = "https://你的租户名.sharepoint.com/sites/你的团队站点"
# 替换为你的Office365账号和密码(注:账号开启MFA时此方式不适用)
credentials = UserCredential("你的邮箱@租户域名.com", "你的密码")

ctx = ClientContext(site_url).with_credentials(credentials)

# 假设你已定义好目标DataFrame
# df = pd.DataFrame(...)

buffer = BytesIO()              
df.to_excel(buffer, index=False)
buffer.seek(0)
file_content = buffer.read()

list_title = "Documents"
target_folder = ctx.web.lists.get_by_title(list_title).root_folder
file_name = "report #123.xlsx"  # 自定义SharePoint端保存的文件名
target_file = target_folder.upload_file(file_name, file_content).execute_query()
print(f"File has been uploaded to url: {target_file.serverRelativeUrl}")

额外说明

如果你的Office365账号开启了多因素认证(MFA),无法使用用户名+密码认证,需改用设备码认证,示例代码片段如下:

from office365.runtime.auth.device_code_provider import DeviceCodeCredentialProvider

client_id = "你的Azure AD应用客户端ID"  # 需先在Azure AD注册应用获取此ID
provider = DeviceCodeCredentialProvider(client_id)
ctx = ClientContext(site_url).with_credentials(provider)
ctx.authenticate()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 11:12:23