读取SharePoint中Excel文件后如何更新?解决wb.save()报错问题
错误原因
openpyxl 的 wb.save() 只支持本地文件路径或内存类文件对象(比如 BytesIO),不直接支持写入 SharePoint 的 Web URL,直接传 URL 就会触发 OSError: [Errno 22] Invalid argument 错误。
修正后的完整代码
import io import datetime from office365.sharepoint.client_context import ClientContext from office365.sharepoint.files.file import File import openpyxl SP_SITE_URL ='https://companyname.sharepoint.com/sites/SiteName' relative_url = "/sites/SiteName/Shared Documents/FolderName" USERNAME = "your_username" PASSWORD = "your_password" # 1. 初始化上下文并完成身份验证 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() # 获取文件夹内的文件列表 files = ClientFolder.files ctx.load(files) ctx.execute_query() # 定位目标Excel文件的服务器相对路径 newest_file_url = '' for myfile in files: if myfile.properties["Name"] == 'Filename.xlsx': newest_file_url = myfile.properties["ServerRelativeUrl"] break # 读取SharePoint上的Excel文件到内存流 response = File.open_binary(ctx, newest_file_url) bytes_file_obj = io.BytesIO() bytes_file_obj.write(response.content) bytes_file_obj.seek(0) # 加载工作簿并修改内容 wb = openpyxl.load_workbook(bytes_file_obj) worksheet = wb['Sheet1'] row_count = worksheet.max_row col_count = worksheet.max_column for i in range(2, row_count+1): for j in range(4, col_count + 1): cellref = worksheet.cell(i, j) cellref.value = datetime.today().strftime('%Y-%m-%d') # 核心:将修改后的内容暂存到内存流,再上传回SharePoint output_stream = io.BytesIO() wb.save(output_stream) output_stream.seek(0) # 将流指针重置到起始位置 # 覆盖原SharePoint文件 target_file = ctx.web.get_file_by_server_relative_url(newest_file_url) target_file.save_binary(output_stream) ctx.execute_query() print("文件已成功更新并保存到SharePoint")
关键逻辑说明
- 内存中转修改内容:用
BytesIO存储修改后的Excel数据,避免本地文件操作,同时适配SharePoint的上传要求。 - 调用官方API写入:通过
target_file.save_binary()方法将内存流内容覆盖回原文件,这是Office365 SDK原生支持的写入方式,能正确处理SharePoint的权限和存储规则。
第三步需求(跨Excel更新)的实现思路
要完成“读取一个Excel的数据更新另一个Excel”,只需重复两次读取流程:
- 先读取源Excel到内存工作簿,提取需要同步的数据
- 读取目标Excel到另一个内存工作簿,把提取的数据写入对应位置
- 最后用上述“内存流+save_binary”的方法,将修改后的目标工作簿保存回SharePoint
内容的提问来源于stack exchange,提问作者Erik Johnsson
相关产品推荐
相关产品推荐

