cannot import name 'save_virtual_workbook' from 'openpyxl.writer.excel'

Question:

Is there an update to the library?

Before it worked perfectly, and today I updated and it no longer loads

I searched but I can’t find any other option

Asked By: francisco solis

||

Answers:

I solve this issue by installing an older version 3.0.10
pip install openpyxl==3.0.10

Answered By: Lalit mahato

Looks like the new recommendation from the developers is to use a temp-file:
https://openpyxl.readthedocs.io/en/3.1/tutorial.html?highlight=save#saving-as-a-stream

update: I ended up having to use this with modifications

from tempfile import NamedTemporaryFile
from openpyxl import Workbook

wb = Workbook()

with NamedTemporaryFile() as tmp:
    tmp.close() # with statement opened tmp, close it so wb.save can open it
    wb.save(tmp.name)
    with open(tmp.name, 'rb') as f:
        f.seek(0) # probably not needed anymore
        new_file_object = f.read()

because the with statement opens the file and then wb.save (which expects a string filename) attempts to open it, resulting in an Exception

Answered By: nmz787

The official recommendation does not work (as-is) on Windows + it uses the filesystem to save the workbook, even if only briefly.

Here a better method in my mind which is all in-memory:

with io.BytesIO() as buffer:
    wb.save(buffer)
    content = buffer.getvalue()

This works because the underlying ZipFile() used here accepts a file-like object in addition to filename.

Answered By: yan-hic
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.