首页 > 解决方案 > 使用 Shareplum 下载、更改文件,然后将文件上传到 sharepoint

问题描述

正如标题所说,我有这个代码

from shareplum import Site
from shareplum import Office365
from shareplum.site import Version

authcookie = Office365('https://mysite.sharepoint.com/', username='username', password='password').GetCookies()
site = Site('https://mysite.sharepoint.com/sites/mysite/', version=Version.v2016, authcookie=authcookie)
folder = site.Folder('Shared Documents/Beta Testing')
file = folder.get_file('practice.xlsx')
with open("practice.xlsx", "wb") as fh:
    fh.write(file)
print('---')
folder.upload_file('xlsx', 'practice.xlsx')

目前它可以很好地下载文件,这太棒了,但是我不知道如何扭转我在打开和下载文件时所做的事情。基本上,我需要能够上传与我以完全相同的格式(在本例中为 xlsx)下载的文件名称完全相同的文件,以便用更新的文档覆盖共享点中的文件。

标签: pythonexcelsharepointshareplum

解决方案


您的帖子表明您要修改文件,因此在修改后保存下载的文件后,您需要对下载的文件进行一些文件处理。完成文件修改后,您需要在“rb”中打开文件,然后将其读入一个变量,该变量将成为调用 folder_obj.upload_file(content, name) 时的内容。

#this is your step to modify the file.
with open("practice.xlsx", "wb") as fh:
    #file modification stuff... pyxlsx?
    fh.write(file)

#open the file and read it into a variable as binary
with open("practice.xlsx", "rb") as file_obj:
    file_as_string = file_obj.read()

#upload the file including the file name and the variable (file_as_string)
folder.upload_file(file_as_string, 'practice.xlsx')

这一直对我有用。如果要更改文件名以包含版本,请通过调用 folder.delete_file("practice.xlsx") 删除旧文件。


推荐阅读