Search code examples
pythonsharepointazure-functionsopenpyxlshareplum

Upload openpyxl workbook object to Sharepoint without save it on pc


I am working with openpyxl and shareplum libraries.

Everything works fine when I save my 'wb' object on my pc and then upload.

1.- save my wb object:

wb.save(filename = 'MyFilename.xlsx')  # <--openpyxl

2.- upload the file saved:

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

def saveSharedFile('MyFilename.xlsx'):
    authcookie = Office365('https://<mysite>.sharepoint.com', username='<my>@<mail>.com.pe', password='<mypassword>').GetCookies()
    site = Site('https://<mysite>.sharepoint.com/sites/<mysite>', version=Version.v365, authcookie=authcookie)
    folder = site.Folder('Documentos Compartidos/<myfolder>')

    with open('MyFilename.xlsx', mode='rb') as file:
        fileContent = file.read()
    folder.upload_file(fileContent, "MyFilenameOnSharepoint.xlsx")

Is there a way to upload my 'wb' objec directly to sharepoint without saving it on my PC before? This is important because I will deploy my .py file on Azure Functions in order to run it automatically.

I tried with NamedTemporaryFile(), BytesIO() and 'pickle' with no success. Thanks in advance.


Solution

  • OK, this is thanks to @GordonAitchJay

    1.- save my wb object:

    buffer = io.BytesIO()
    wb.save(buffer)  # <--openpyxl
    

    2.- upload the file saved:

    from shareplum import Site
    from shareplum import Office365
    from shareplum.site import Version
    import io
    
    def saveSharedFile(buffer, 'MyFilename.xlsx'):
        authcookie = Office365('https://<mysite>.sharepoint.com', username='<my>@<mail>.com.pe', password='<mypassword>').GetCookies()
        site = Site('https://<mysite>.sharepoint.com/sites/<mysite>', version=Version.v365, authcookie=authcookie)
        folder = site.Folder('Documentos Compartidos/<myfolder>')
    
        folder.upload_file(buffer.getvalue(),'MyFilename.xlsx')