Office365-REST-Python-Client
Office365-REST-Python-Client copied to clipboard
how can I update and save the change to an excel file in sharepoint after read
After I use code below to read the excel file in sharepoint, how can I write updates to the same excel file
SP_SITE_URL ='https://xxx.sharepoint.com/sites/xxx'
relative_url = "/sites/xxx/Shared Documents/FOLDER"
# 1. Create a ClientContext object and use the user’s credentials for authentication
ctx = ClientContext(SP_SITE_URL).with_user_credentials(USERNAME, PASSWORD)
ClientFolder = ctx.web.get_folder_by_server_relative_path(relative_url)
ctx.load(ClientFolder)
ctx.execute_query()
#if you want to get the files in the folder
files = ClientFolder.files
print(files)
ctx.load(files)
ctx.execute_query()
newest_file_url = ''
for myfile in files:
if myfile.properties["Name"] == 'xxx.xlsx':
newest_file_url = myfile.properties["ServerRelativeUrl"]
# Get Excel File by newest_file_url identified above
response= File.open_binary(ctx, newest_file_url)
# save data to BytesIO stream
bytes_file_obj = io.BytesIO()
bytes_file_obj.write(response.content)
bytes_file_obj.seek(0)
```
Yes - read the workbook, edit it, then write the content back to the same file (overwrite). There's no SharePoint "save in place" cell editor in the library (Excel Services REST was retired in 2022; the supported in-place API is Microsoft Graph - see examples/onedrive/excel/), so the standard pattern is download → edit → upload.
import io
import pandas as pd
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.files.file import File
ctx = ClientContext(site_url).with_username_and_password(tenant, client_id, username, password)
file_url = "/sites/xxx/Shared Documents/FOLDER/xxx.xlsx"
1) read
df = pd.read_excel(io.BytesIO(File.open_binary(ctx, file_url).content), sheet_name="Sheet1")
2) modify
df.loc[df["Status"] == "New", "Status"] = "Done"
3) write the updated workbook back to the same file
buffer = io.BytesIO()
with pd.ExcelWriter(buffer, engine="openpyxl") as writer:
df.to_excel(writer, index=False, sheet_name="Sheet1")
File.save_binary(ctx, file_url, buffer.getvalue())