0

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.

  • 1
    Openpyxl only supports working with files on a file system. – Charlie Clark Aug 22 '22 at 10:30
  • 1
    I don't understand why using `io.BytesIO` doesn't work. Save the workbook to the buffer: `buffer = io.BytesIO(); wb.save(buffer)`, and then upload it: `folder.upload_file(buffer.getvalue(), "MyFilenameOnSharepoint.xlsx")` – GordonAitchJay Sep 05 '22 at 04:37
  • 1
    @GordonAitchJay Thanks man!! Great comment right to the point!! I did not add ".getvalue()" that is why It didnt work. Life saver!! – walther leonardo Sep 09 '22 at 17:36

1 Answers1

1

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')