XlsxWriter object save as http response to create download in Django?
I think you're asking about how to create an excel file in memory using xlsxwriter
and return it via HttpResponse
. Here's an example:
try:
import cStringIO as StringIO
except ImportError:
import StringIO
from django.http import HttpResponse
from xlsxwriter.workbook import Workbook
def your_view(request):
# your view logic here
# create a workbook in memory
output = StringIO.StringIO()
book = Workbook(output)
sheet = book.add_worksheet('test')
sheet.write(0, 0, 'Hello, world!')
book.close()
# construct response
output.seek(0)
response = HttpResponse(output.read(), mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
response['Content-Disposition'] = "attachment; filename=test.xlsx"
return response
tempfile.tempdir
internally - this cause problems on google app engine: please see #17014555. –
Hourglass :-)
A fully in-memory file assembly without access to a directory would be tricky but probably doable. I'll put it up high on the TODO list. –
Collie 0, 0
specifies the cell, in this case A1. –
Withdrawn A little update on @alecxe response for Python 3 (io.BytesIO instead of StringIO.StringIO) and Django >= 1.5 (content_type instead of mimetype), with the fully in-memory file assembly that has since been implemented by @jmcnamara ({'in_memory': True}) !
Here is the full example :
import io
from django.http.response import HttpResponse
from xlsxwriter.workbook import Workbook
def your_view(request):
output = io.BytesIO()
workbook = Workbook(output, {'in_memory': True})
worksheet = workbook.add_worksheet()
worksheet.write(0, 0, 'Hello, world!')
workbook.close()
output.seek(0)
response = HttpResponse(output.read(), content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
response['Content-Disposition'] = "attachment; filename=test.xlsx"
output.close()
return response
in_memory
actually uses StringIO. However, the final file output is determined by the first parameter to Workbook()
. If it's a string, a file with that name is created (even if in_memory
is used). If it's a StringIO, the final file will be stored in memory. The text in this example helped –
Drosophila output
. I don't think it's necessary, but its good practice for memory management. In the StringIO docs they demonstrate closing the object. –
Drosophila I think you're asking about how to create an excel file in memory using xlsxwriter
and return it via HttpResponse
. Here's an example:
try:
import cStringIO as StringIO
except ImportError:
import StringIO
from django.http import HttpResponse
from xlsxwriter.workbook import Workbook
def your_view(request):
# your view logic here
# create a workbook in memory
output = StringIO.StringIO()
book = Workbook(output)
sheet = book.add_worksheet('test')
sheet.write(0, 0, 'Hello, world!')
book.close()
# construct response
output.seek(0)
response = HttpResponse(output.read(), mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
response['Content-Disposition'] = "attachment; filename=test.xlsx"
return response
tempfile.tempdir
internally - this cause problems on google app engine: please see #17014555. –
Hourglass :-)
A fully in-memory file assembly without access to a directory would be tricky but probably doable. I'll put it up high on the TODO list. –
Collie 0, 0
specifies the cell, in this case A1. –
Withdrawn When it comes to Django, you can even do without the whole StringIO
shenanigans. HttpResponse
behaves just like a StringIO in that respect:
from django.http import HttpResponse
from xlsxwriter.workbook import Workbook
def your_view(request):
# your view logic here
# create the HttpResponse object ...
response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = "attachment; filename=test.xlsx"
# .. and pass it into the XLSXWriter
book = Workbook(response, {'in_memory': True})
sheet = book.add_worksheet('test')
sheet.write(0, 0, 'Hello, world!')
book.close()
return response
Addendum: You need to specify {'in_memory': True}
or you might get HttpResponse has no attribute seek()
. Thanks @Jeb
It's better to follow the official doc from jmcnamara (package developer)
I use nodejs with reportProgress: True
. My Django code is like this;
output = io.BytesIO()
workbook = xlsxwriter.Workbook(output, {'in_memory': True})
worksheet = workbook.add_worksheet()
worksheet.write(y, x, column_name)
worksheet.write(y, x, column_name)
workbook.close()
output.seek(0)
return FileResponse(output.read(), filename="reservations.xlsx")
If you do this then you can use like this
A simple Django View class to write an Excel file using the XlsxWriter module.
import io
from django.http import HttpResponse
from django.views.generic import View
import xlsxwriter
def get_simple_table_data():
# Simulate a more complex table read.
return [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
class MyView(View):
def get(self, request):
# Create an in-memory output file for the new workbook.
output = io.BytesIO()
# Even though the final file will be in memory the module uses temp
# files during assembly for efficiency. To avoid this on servers that
# don't allow temp files, for example the Google APP Engine, set the
# 'in_memory' Workbook() constructor option as shown in the docs.
workbook = xlsxwriter.Workbook(output)
worksheet = workbook.add_worksheet()
# Get some data to write to the spreadsheet.
data = get_simple_table_data()
# Write some test data.
for row_num, columns in enumerate(data):
for col_num, cell_data in enumerate(columns):
worksheet.write(row_num, col_num, cell_data)
# Close the workbook before sending the data.
workbook.close()
# Rewind the buffer.
output.seek(0)
# Set up the Http response.
filename = 'django_simple.xlsx'
response = HttpResponse(
output,
content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
)
response['Content-Disposition'] = 'attachment; filename=%s' % filename
return response
© 2022 - 2024 — McMap. All rights reserved.