使用Openpyxl读取SharePoint上Excel文件出现403错误如何解决
问题原因
- 当前使用的是SharePoint文件的网页预览URL,不是直接下载地址,且urllib请求未携带SharePoint身份验证凭证,触发权限拦截返回403错误。
- 原有代码中URL未加引号属于语法错误,同时调用的
get_sheet_names()是openpyxl已废弃的方法。
解决步骤
1. 安装依赖库
需要安装Office365 SharePoint验证库处理身份权限:
pip install office365-rest-python-client openpyxl
2. 调整代码实现
from office365.sharepoint.client_context import ClientContext from office365.runtime.auth.user_credential import UserCredential from openpyxl import load_workbook from io import BytesIO # 替换为你的实际配置参数 site_url = "https://company.sharepoint.com/sites/global" file_relative_path = "tasks/ADT/SEPT ALL ROB.xlsx" user_name = "你的企业邮箱地址" user_password = "你的账号登录密码" # 验证并下载文件到内存 ctx = ClientContext(site_url).with_credentials(UserCredential(user_name, user_password)) file_content = ctx.web.get_file_by_server_relative_path(file_relative_path).download().execute_query() # openpyxl读取文件 wb = load_workbook(filename=BytesIO(file_content.value)) sheet_list = wb.sheetnames print(sheet_list)
注意事项
- 如果账号开启了多因素认证,无法直接使用用户名密码验证,需要在Azure后台注册应用,获取client_id和client_secret,使用
ClientCredential替换UserCredential即可,同时要为注册的应用分配对应SharePoint站点的文件读取权限。 - 必须使用文件的服务器相对路径,不要直接用原预览页URL,避免请求跳转到登录页导致验证失败。
内容的提问来源于stack exchange,提问作者Bobby
相关产品推荐
相关产品推荐

