Use save_virtual_workbook and optimized writer

Issue #375 invalid
17372132 created an issue

Can I combine optimized writer and save_virtual_workbook?

The cell values are not saved in this script:

def get(self, request, *args, **kwargs):
    from openpyxl.writer.excel import save_virtual_workbook
    from openpyxl import Workbook
    wb = Workbook(write_only=True)
    ws = wb.create_sheet()
    ws.title = "MyModel"
    for irow in range(100):
        ws.append(['%d' % i for i in range(200)])
    response = HttpResponse(save_virtual_workbook(wb), content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response['Content-Disposition'] = 'attachment; filename=line_items.xlsx'
    return response

and I guess the problem is

Comments (5)

  1. CharlieC

    No, you cannot combine the two approaches and I'm not sure how much sense it would make: the write_only option is about reducing memory use whereas a save_virtual_workbook() loads everything into memory to make it easier to return it as a response. Depending on the configuration of your web server you can easily create a workbook and serve the file.'line_items.xlsx')
    response = HTTPResponse(open('line_items.xlsx', 'rb'))
    response['Content-Disposition'] = 'attachment; filename=line_items.xlsx'
  2. 17372132 reporter

    I am trying to download a huge amount of data from a Django model in a workbook. The workbook doesn't exists so I think the solution is to use save_virtual_workbook. It will be too slow if I'm not using the optimized writer so how is it possible to save a 'virtual' workbook and still use the optimized writer?

  3. CharlieC

    The code I proposed should work with the write_only mode. If you look at the code you'll see the save_virtual_workbook() doesn't do anything special but you might be able pass the file to the server (or open it and .read() just like you would with any other file and delete it afterwards. Some WSGI servers will allow you to pass the file handling to the HTTP server just as with static resources.

    The mailing list is a better place for discussions.

  4. Log in to comment