Saving openpyxl file via text and filestream

In openpyxl 2.6 calling the save_virtual_workbook method issues the following warning:

DeprecationWarning: Call to deprecated function save_virtual_workbook (Use a NamedTemporaryFile).

At some point save_virtual_workbook will be removed from openpyxl.

In Python 3 typical usage to save an openpyxl workbook to a filestream becomes:

from io import BytesIO
from tempfile import NamedTemporaryFile
from openpyxl import Workbook

wb = Workbook()
with NamedTemporaryFile() as tmp:
    wb.save(tmp.name)
    output = BytesIO(tmp.read())

After looking at the implementation of the WorkBook save method, the ‘filename’ is sent straight to ZipFile which accepts a path or file-like object so there is no need for a NamedTemporaryFile and simply use in-memory BytesIO:

from io import BytesIO
from openpyxl import Workbook

wb = Workbook()
virtual_workbook = BytesIO()
wb.save(virtual_workbook)

# now use virtual_workbook to send to a stream; email attachment, etc

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)