我的目标是使用 Python 读取和写入 SharePoint 中其他用户将访问的 Excel 文件。 我在本地计算机上使用
Pandas
进行读取和 xlWings
进行写入,开发了一个问题的解决方案。 现在我正在尝试将其移至 SharePoint。
我已经阅读了一些教程/问题答案(即here和here)并且可以进行身份验证。 我已经根据
this答案更新了我的
url
,但没有运气。
这是我收到的错误消息:
{
"error": {
"code": "invalidRequest",
"message": "Invalid request"
}
}
'value'
之前,我的网址以
/workbook/tables('Plant_3')
结尾,基于此 answer,但我收到以下错误:
"error": {
"code": "BadRequest",
"message": "Open navigation properties are not supported on OpenTypes. Property name: 'tables'.",
我相信该错误是因为我的文件没有表,并且 url 试图链接到该对象/集合。
这是我的代码:
from msal import ConfidentialClientApplication
import requests
import json
import pandas as pd
import configparser
config = configparser.ConfigParser()
config.read('config.ini')
client_id = config['entra_auth']['client_id']
client_secret = config['entra_auth']['client_secret']
tenant_id = config['entra_auth']['tenant_id']
msal_scope = ['https://graph.microsoft.com/.default']
msal_app = ConfidentialClientApplication(client_id=client_id,
authority=f"https://login.microsoftonline.com/{tenant_id}",
client_credential=client_secret, )
result = msal_app.acquire_token_silent(scopes=msal_scope,
account=None)
if not result:
result = msal_app.acquire_token_for_client(scopes=msal_scope)
if 'access_token' in result:
access_token = result['access_token']
else:
raise Exception("Failed to acquire token")
headers = {'Authorization': f'Bearer {access_token}'}
site_id = config['site']['site_id'] # https://www.powertechtips.com/check-site-id-sharepoint/
# https://answers.microsoft.com/en-us/msoffice/forum/all/how-can-i-find-the-library-id-on-our-sharepoint/701e68f3-954f-490c-b3cb-ceb8bd5601d1
document_library_id = config['site']['document_library_id']
doc_id = config['site']['doc_id'] # from document details
file_name = config['site']['file_name']
# create url
url = f"https://graph.microsoft.com/v1.0/sites/{tenant_id}:/sites/{site_id}:/drives/{document_library_id}:/root/{file_name}:/workbook/tables('Sheet1')/rows"
# Make a GET request to the Microsoft Graph API to read the Excel file as a pandas dataframe
response = requests.get(url, headers=headers)
try: # how I want it to go
data = response.json()["value"]
df = pd.DataFrame(data)
print(df)
except Exception as e:
print(json.dumps(response.json(), indent=4))
print(e)
我创建了一个应用程序注册并添加了与您相同的API权限,如下所示:
在 SharePoint 中,我有一个名为
test.xlsx
的 Excel 文件,其中包含以下数据:
最初,当我运行你的代码来检索上述 excel 文件数据时,我也遇到了同样的错误:
为了解决该错误,我运行了以下modified python代码并成功获得了excel数据的响应,如下所示:
from msal import ConfidentialClientApplication
import requests
import pandas as pd
import configparser
# Read the config file for credentials and details
config = configparser.ConfigParser()
config.read('config.ini')
client_id = config['entra_auth']['client_id']
client_secret = config['entra_auth']['client_secret']
tenant_id = config['entra_auth']['tenant_id']
# Set up Microsoft Graph authentication
msal_scope = ['https://graph.microsoft.com/.default']
msal_app = ConfidentialClientApplication(client_id=client_id,
authority=f"https://login.microsoftonline.com/{tenant_id}",
client_credential=client_secret)
result = msal_app.acquire_token_silent(scopes=msal_scope, account=None)
if not result:
result = msal_app.acquire_token_for_client(scopes=msal_scope)
if 'access_token' in result:
access_token = result['access_token']
else:
raise Exception("Failed to acquire token")
# Prepare request headers with the acquired access token
headers = {'Authorization': f'Bearer {access_token}'}
# Get necessary configuration data for the SharePoint file
site_id = config['site']['site_id']
document_library_id = config['site']['document_library_id']
doc_id = config['site']['doc_id']
# Use 'usedRange' to automatically detect the range with data
url = f"https://graph.microsoft.com/v1.0/sites/{site_id}/drives/{document_library_id}/items/{doc_id}/workbook/worksheets('Sheet1')/usedRange"
# Make a GET request to Microsoft Graph API to read the worksheet range
response = requests.get(url, headers=headers)
# Extract only the 'values' part of the response
try:
data = response.json().get('values', [])
# If data is found, convert it to a pandas DataFrame and print it
if data:
df = pd.DataFrame(data[1:], columns=data[0]) # First row as column headers
print(df)
else:
print("No data found.")
except Exception as e:
print(f"Error: {e}")
回复: