Saving openpyxl file via text and filestream

前端 未结 5 1133
清酒与你
清酒与你 2021-02-01 16:49

I\'m building OpenPyXL into an application that expects a string containing the content of the excel file, for it to write via file stream.

From my investigation into th

5条回答
  •  广开言路
    2021-02-01 17:11

    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
    
    

提交回复
热议问题