构建一个小型 MS Graph 脚本,用于更新存储在 OneDrive 中的 Excel 工作表中的字段。 如下面的代码所示,它将字段 A1 更新为“200”。
这很大程度上是一个 WIP,后续将会更新为其他内容。
代码:
from msal import ConfidentialClientApplication
import requests
def get_access_token(client_id, tenant_id, client_secret):
"""
Authenticate and obtain an access token using MSAL for a confidential client.
"""
authority = f"https://login.microsoftonline.com/{tenant_id}"
app = ConfidentialClientApplication(
client_id,
authority=authority,
client_credential=client_secret
)
result = app.acquire_token_for_client(scopes=["https://graph.microsoft.com/.default"])
if "access_token" in result:
return result['access_token']
else:
raise Exception("Failed to acquire access token: " + result.get("error_description", ""))
def create_session(access_token, user_id, file_id):
"""
Create a session for an Excel file to make changes that persist on a specified user's OneDrive.
"""
url = f"https://graph.microsoft.com/v1.0/users/{user_id}/drive/items/{file_id}/workbook/createSession"
headers = {"Authorization": f"Bearer {access_token}", "Content-Type": "application/json"}
data = {"persistChanges": True}
response = requests.post(url, headers=headers, json=data)
if response.status_code == 200:
return response.json()['id']
else:
raise Exception("Failed to create session: " + response.text)
def update_cell(access_token, user_id, file_id, session_id, sheet_name, cell_address, value):
"""
Update a specific cell in the Excel sheet using a session on a specified user's OneDrive.
"""
url = f"https://graph.microsoft.com/v1.0/users/{user_id}/drive/items/{file_id}/workbook/worksheets/{sheet_name}/range(address='{cell_address}')"
headers = {
"Authorization": f"Bearer {access_token}",
"Content-Type": "application/json",
"workbook-session-id": session_id
}
data = {"values": [[value]]}
response = requests.patch(url, headers=headers, json=data)
if response.status_code != 204:
raise Exception("Failed to update cell: " + response.text)
def close_session(access_token, user_id, file_id, session_id):
"""
Close the session after modifications are made to ensure changes persist on a specified user's OneDrive.
"""
url = f"https://graph.microsoft.com/v1.0/users/{user_id}/drive/items/{file_id}/workbook/closeSession"
headers = {
"Authorization": f"Bearer {access_token}",
"Content-Type": "application/json",
"workbook-session-id": session_id
}
response = requests.post(url, headers=headers)
if response.status_code != 204:
raise Exception("Failed to close session: " + response.text)
def main():
"""
Main function to execute the process.
"""
CLIENT_ID = 'REMOVED'
TENANT_ID = 'REMOVED'
CLIENT_SECRET = 'REMOVED'
USER_ID = 'REMOVED'
FILE_ID = 'REMOVED' # Directly use the known file ID
SHEET_NAME = 'Sheet1'
CELL_ADDRESS = 'A1'
NEW_VALUE = '200'
try:
access_token = get_access_token(CLIENT_ID, TENANT_ID, CLIENT_SECRET)
session_id = create_session(access_token, USER_ID, FILE_ID)
update_cell(access_token, USER_ID, FILE_ID, session_id, SHEET_NAME, CELL_ADDRESS, NEW_VALUE)
print("Cell updated successfully!")
close_session(access_token, USER_ID, FILE_ID, session_id)
print("Session closed successfully!")
except Exception as e:
print(str(e))
if __name__ == "__main__":
main()
我遇到的错误是:
Failed to create session: {"error":{"code":"AccessDenied","message":"Could not obtain a WAC access token.","innerError":{"date":"2024-05-11T13:23:08","request-id":"89fd141b-9888-4a5d-9aa6-3951878c1c45","client-request-id":"89fd141b-9888-4a5d-9aa6-3951878c1c45"}}}
目前遇到了障碍。 任何帮助将不胜感激!
目的是能够验证、查找文件并更新单元格中的数据。 以上所有内容都是通过变量动态更改的(参见代码)。
我已检查了与此相关的权限,Microsoft Graph 都能够访问(读取)用户的信息和用户的 OneDrive。我一直在使用 Graph Explorer 来检查(并授予管理员批准)权限。
Excel 文件的文件扩展名是什么,例如 .xlsx 或 .xltm?
如果文件不是 .xlsx 格式,请考虑将其转换为 .xlsx 并使用上述 API