Silwestpl Silwestpl - 4 months ago 89
Python Question

Django: openpyxl saving workbook as attachment

Hi I have a quick question. I didn't find answer in internet maybe someone of you can help me.

So i want to save workbook as attachment but I don't know how lets see an example :

from openpyxl import Workbook
from openpyxl.cell import get_column_letter
wb = Workbook(encoding='utf-8')
dest_filename = 'file.xlsx'
ws = wb.worksheets[0]
ws.title = "range names"
for col_idx in xrange(1, 40):
col = get_column_letter(col_idx)
for row in xrange(1, 600):
ws.cell('%s%s'%(col, row)).value = '%s%s' % (col, row)
ws = wb.create_sheet()
ws.title = 'Pi'
ws.cell('F5').value = 3.14


Then I tried :

response = HttpResponse(wb, content_type='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename="foo.xls"'
return response


It's returning xlsx file indeed but in file there is only object adres not the content of file:

<openpyxl.workbook.Workbook object at 0x00000000042806D8>


Can someone help ?

Answer

Give it a try:

from openpyxl.writer.excel import save_virtual_workbook
...
response = HttpResponse(save_virtual_workbook(wb), content_type='application/vnd.ms-excel')

save_virtual_workbook was specially designed for your use case. Here's a docstring:

"""Return an in-memory workbook, suitable for a Django response."""