使用Python读取OneDrive 365上的Excel文件

5

我希望能够读取位于Onedrive 365上的Excel文件。

我在网上阅读了很多资源,但没有一个有效的方法!!!

我的现有代码如下:

from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.file import File 

url = 'https://yoursharepointsite.com/sites/documentsite'
username = 'yourusername'
password = 'yourpassword'
relative_url = '/sites/documentsite/Documents/filename.xlsx'

import io
import pandas as pd

response = File.open_binary(ctx, relative_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 file into pandas dataframe
df = pd.read_excel(bytes_file_obj)

我遇到了以下错误。
out>>> ModuleNotFoundError: No module named 'web'

你有想法吗?


你尝试过执行 pip install web 吗? - tykom
是的,我尝试过了,但出现了以下信息:"无法找到满足要求的版本 web(来自版本:) 没有找到匹配的发行版 web"。 - noliverte
问题出在那个模块上。所以你要么找到一个可用的版本,要么使用不依赖它的东西。web 的 PyPI 条目看起来好像不应该用于任何事情。 - tykom
1
你在这里使用的是Python3还是Python2?我无法在Python3中导入“AuthenticationContext”,因为它使用了“urlparse”。在Python3中,可以通过“from urlib.parse import urlparse”来访问此模块。 - pele88
1个回答

0

您需要先进行身份验证,然后使用连接器返回文件:

from office365.runtime.auth.user_credential import UserCredential
from office365.sharepoint.client_context import ClientContext

site_url = "https://yoursharepointsite.com" + f"/sites/{documentsite}/"
ctx = ClientContext(site_url).with_credentials(
    UserCredential(username, password=password))
ctx.load(ctx.web)
ctx.execute_query()

from office365.sharepoint.files import file
import io

file_url = file_dl if dynamic else f'/sites/{documentsite}/{file_dl}'
response = file.File.open_binary(ctx, file_url)
bytes_file_obj = io.BytesIO()
bytes_file_obj.write(response.content)
bytes_file_obj.seek(0)
return bytes_file_obj

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接