[英]Unable to read Excel from SharePoint using office365 with Python
Using this answer , I am attempting to read an Excel document from SharePoint into a pandas
dataframe. My code is as follows:使用此答案,我试图将 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)
When it gets to the ctx.execute_query()
line, I get this error:当它到达
ctx.execute_query()
行时,我收到此错误:
ClientRequestException: (None, None, '404 Client Error: Not Found for url: https://name1.sharepoint.com/sites/name2/name3/name4.xlsx/_api/Web')
I have tried different documents, but I get the same response.我尝试了不同的文件,但得到了相同的答复。
In the answer linked at the beginning, the url
has a cid
parameter, which I am wondering if that is the problem.在开头链接的答案中,
url
有一个cid
参数,我想知道这是否是问题所在。 But I haven't been able to find a value to use as my cid
, nor have I been able to find out what a cid
is.但是我一直无法找到用作我的
cid
的值,也无法找出cid
是什么。 I think the issue maybe in the url
variable, but I'm not exactly sure how.我认为这个问题可能在
url
变量中,但我不确定如何。 Any suggestions much appreciated!非常感谢任何建议!
It seems that the provided url for context generation is incorrect.似乎为上下文生成提供的 url 不正确。 Please have a try following snnipet:
请尝试以下 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())
Full code: https://github.com/kongmengfei/sharedproject/blob/master/PythonConsole-uploadfileSPO/PythonApplication2/ctx_auth_acquire_token.py完整代码: https://github.com/kongmengfei/sharedproject/blob/master/PythonConsole-uploadfileSPO/PythonApplication2/ctx_auth_acquire_token.py
BR BR
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.