I am trying to create an export to excel functionality in my django view as follows:
def export_myreport(request, sd, ed):
from xlsxwriter.workbook import Workbook
import cStringIO as StringIO
from django.utils.encoding import smart_str
# create a workbook in memory
output = StringIO.StringIO()
wb = Workbook(output)
bg = wb.add_format({'bg_color': '#9CB640', 'font_color': 'black'})
bg2 = wb.add_format({'bg_color': '#FFFFFF', 'font_color': 'black'})
ws = wb.add_worksheet('My Report')
row_num = 0
summary = MyModel.objects.filter(time__range = (sd, ed)).select_related()
row_num += 2
row = [
smart_str(u"Time"),
smart_str(u"Item"),
smart_str(u"User")
]
for col_num in xrange(len(row)):
ws.write(row_num, col_num, row[col_num], bg)
for s in summary:
row_num += 1
row2 = [
s.time,
s.model_name,
s.user.first_name
]
for col_num in xrange(len(row2)):
ws.write(row_num, col_num, row2[col_num], bg2)
wb.close()
output.seek(0)
response = HttpResponse(output.read(), content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
response['Content-Disposition'] = "attachment; filename=myreport.xlsx"
return response
But i am getting some issues with the DateTime formatting! Perhaps something i am missing here?
Here is the error i get:
TypeError at /myapp/export_myreport/2015-05-01/2015-05-19
can't subtract offset-naive and offset-aware datetimes
EDIT:
This is how i am calling the url in my html:
<a href="export_myreport/{{begindate}}/{{enddate}}" class="btn btn-default pull-right" role="button">Export to XLSX</a>
Here the {{begindate}}
and {{enddate}}
are angular variables.
Excel, and thus XlsxWriter, doesn't support timezones in dates/times.
So you will need to remove or adjust the timezone from the datetime before passing it to XlsxWriter.
Something like this from the pytz docs:
Probably this would be better handled in Django though rather than adjusting all datetime data prior to passing it to XlsxWriter. Maybe someone else can add a suggestion on that.