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

如何通过Python office365 API下载SharePoint的Docx文件并保存到本地

问题原因排查与修复方案

一、无本地文件生成的问题排查

  • 先校验权限与路径有效性:确认应用注册时已经授予对应SharePoint站点的Files.ReadWrite.All应用权限且完成管理员同意;SharePoint文件路径不要手动转义空格为%20,SDK会自动处理转义,直接写"/sites/sitename/Shared Documents/test/word_doc.docx"即可,手动转义会导致404找不到文件,返回空内容自然无法生成本地文件。
  • 检查本地路径权限:优先选择非系统盘路径(比如D:/test/file.docx)测试,避免C盘用户目录的权限拦截导致写文件操作被静默拦截。
  • 增加返回结果校验逻辑,提前识别无效内容:
# 先校验目标文件是否可以正常访问
target_file = ctx.web.get_file_by_server_relative_path("/sites/sitename/Shared Documents/test/word_doc.docx")
ctx.load(target_file)
ctx.execute_query()
print(f"获取到的文件大小:{target_file.length}字节")
if target_file.length == 0:
    raise Exception("未获取到有效文件内容,请检查路径或权限")

二、二进制内容转可用docx的处理

File.open_binary返回的content本身就是docx文件的完整二进制编码,不需要额外做格式转换,只要成功写入本地路径就是可以直接打开编辑的标准docx文件。
修正后的完整下载代码如下:

from office365.runtime.auth.client_credential import ClientCredential
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.files.file import File

# 配置参数
site_url = "你的SharePoint站点地址"
client_id = "你的应用客户端ID"
client_secret = "你的应用客户端密钥"
sp_file_path = "/sites/sitename/Shared Documents/test/word_doc.docx"
local_save_path = "D:/test/edited_file.docx"

# 身份认证
ctx = ClientContext(site_url).with_credentials(ClientCredential(client_id, client_secret))

# 下载文件
try:
    target_file = ctx.web.get_file_by_server_relative_path(sp_file_path)
    ctx.load(target_file)
    ctx.execute_query()
except Exception as e:
    print(f"文件读取失败:{e}")
    exit()

response = File.open_binary(ctx, target_file.server_relative_url)
with open(local_save_path, "wb") as f:
    f.write(response.content)
print(f"文件已保存至{local_save_path},可直接打开编辑")

三、编辑完成后上传回SharePoint的实现代码

def upload_to_sharepoint(ctx, local_file_path, sp_folder_path):
    folder = ctx.web.get_folder_by_server_relative_url(sp_folder_path)
    with open(local_file_path, "rb") as f:
        content = f.read()
    file_name = local_file_path.split("/")[-1]
    folder.upload_file(file_name, content).execute_query()
    print(f"{file_name}已上传至SharePoint路径{sp_folder_path}")

# 调用示例
sp_target_folder = "/sites/sitename/Shared Documents/test"
upload_to_sharepoint(ctx, local_save_path, sp_target_folder)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 04:00:02