无法使用带有 Python 的 office365 从 SharePoint 读取 Excel

Unable to read Excel from SharePoint using office365 with Python

使用此 ,我试图将 Excel 文档从 SharePoint 读取到 pandas 数据框中。我的代码如下:

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

#target url taken from sharepoint and credentials
url = "https://name1.sharepoint.com/sites/name2/name3/name4.xlsx"
username = 'a.b@name1.com'
password = 'Pa55word'

ctx_auth = AuthenticationContext(url)
if ctx_auth.acquire_token_for_user(username, password):
  ctx = ClientContext(url, ctx_auth)
  web = ctx.web
  ctx.load(web)
  ctx.execute_query()
  print("Authentication successful")

response = File.open_binary(ctx, url)

#save data to BytesIO stream
bytes_file_obj = io.BytesIO()
bytes_file_obj.write(response.content)
bytes_file_obj.seek(0) #set file object to start

#read excel file and each sheet into pandas dataframe 
df = pd.read_excel(bytes_file_obj, sheetname = None)

当它到达 ctx.execute_query() 行时,我得到这个错误:

ClientRequestException: (None, None, '404 Client Error: Not Found for url: https://name1.sharepoint.com/sites/name2/name3/name4.xlsx/_api/Web')

我尝试了不同的文档,但得到的响应都是一样的。

在开头链接的答案中,url 有一个 cid 参数,我想知道这是否是问题所在。但是我一直没能找到用作我的 cid 的值,也一直没能找出 cid 是什么。我认为问题可能出在 url 变量中,但我不太确定是怎么回事。非常感谢任何建议!

似乎为上下文生成提供的 url 不正确。请尝试以下 snnipet:

tenant_url= "https://{tenant}.sharepoint.com"
ctx_auth = AuthenticationContext(tenant_url)

site_url="https://{tenant}.sharepoint.com/sites/{yoursite}"

if ctx_auth.acquire_token_for_user("username","password"):
  request = ClientRequest(ctx_auth)
  options = RequestOptions("{0}/_api/web/".format(site_url))
  options.set_header('Accept', 'application/json')
  options.set_header('Content-Type', 'application/json')
  data = request.execute_request_direct(options)
  s = json.loads(data.content)
  web_title = s['Title']
  print("Web title: " + web_title)
else:
  print(ctx_auth.get_last_error())

完整代码:https://github.com/kongmengfei/sharedproject/blob/master/PythonConsole-uploadfileSPO/PythonApplication2/ctx_auth_acquire_token.py

BR