I've been scratching my head far too long with this one. Here it goes -
I am trying to export a user model class(as excel sheet), after making some changes to it then returning it as HttpResponse object for download. Here is my view code:
if request.method == 'POST':
form = ExportStudentscsv(request.POST)
if form.is_valid():
data = form.cleaned_data
#get course from dropdown value
course = data.get('course')
# find course id based on course title
courseid = Course.objects.get(title=course)
#find groups using course id
groups = Groups.objects.filter(course=courseid)
desiredintake = data.get('desiredintake')
intakeyear = data.get('intakeyear')
user_resource = UserResource()
queryset = User.objects.filter(desiredintake=desiredintake, intakeyear=intakeyear, role=4)
if not queryset:
return page_not_found(request, "Bad Request")
dataset = user_resource.export(queryset)
dataset.xls
response = HttpResponse(dataset.xls, content_type='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename="students.xls"'
workbook = xlsxwriter.Workbook(response, {'in_memory': True})
worksheet = workbook.add_worksheet('Groups')
worksheet.data_validation('B11', {'validate': 'list',
'source': ['open', 'high', 'close']})
workbook.close()
response['content_type'] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
response['Content-Disposition'] = 'attachment; filename=students.xls'
return response
else:
args = {'form': form}
return render(request, 'epitaadmin/export_studentscsv.html', args)
I followed the approach given in the third answer given in this post XlsxWriter object save as http response to create download in Django, but no luck. I don't get the data-validation changes made here -
workbook = xlsxwriter.Workbook(response, {'in_memory': True})
worksheet = workbook.add_worksheet('Groups')
worksheet.data_validation('B11', {'validate': 'list',
'source': ['open', 'high', 'close']})
workbook.close()
ie. the dropdown I am trying to create does not reflect in my downloaded students.xls file.
In the second answer of the same post XlsxWriter object save as http response to create download in Django , the author has given an example of creating a new workbook and downloading it with the changes done using BytesIO. I wonder can I use this approach with an existing workbook using BytesIO?
I have also tried using OpenPyXl library for this task, as it turns out no luck with that either. I found this post with an approach using OpenPyXl here Return openpyxl workbook object as HttpResponse in django. Is it possible? , One interesting thing i found was
from openpyxl.writer.excel import save_virtual_workbook
I was wondering is there a similar thing like save_virtual_workbook
for xlsxwriter library so I can save my workbook in the response like
response = HttpResponse(content=save_virtual_workbook(workbook), mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
Can someone please help me out with this problem?