簡體   English   中英

無法使用 office365 和 Python 從 SharePoint 讀取 Excel

[英]Unable to read Excel from SharePoint using office365 with Python

使用此答案,我試圖將 Excel 文檔從 SharePoint 讀取到pandas dataframe。我的代碼如下:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM