如何将Django 1.7中的queryset导出到xls文件? [英] How to export queryset in Django 1.7 to xls file?
问题描述
我将Django 1.7.1与Python 3.4结合使用。我想将搜索结果导出到Excel文件。
我在view.py中有此功能。
I using Django 1.7.1 with Python 3.4. I would like to export search results to Excel file. I have this function in view.py
def car_list(request):
page = request.GET.get('page')
search = request.GET.get('search')
if search is None:
cars= Car.objects.filter(plate__isnull = False ).order_by('-created_date')
else:
cars= Car.objects.filter(plate__contains = search ).order_by('-created_date')
paginator = Paginator(cars, 100) # Show 100 contacts per page
try:
cars= paginator.page(page)
except PageNotAnInteger:
#if page is not an integer, deliver first page
cars= paginator.page(1)
except EmptyPage:
#if page is out of the range, deliver last page
cars= paginator.page(paginator.num_pages)
if request.REQUEST.get('excel'):
# excel button clicked
return download_workbook(request, cars)
return render_to_response('app/list.html', {'cars': cars}, context_instance=RequestContext(request))
from .utils import queryset_to_workbook
def download_workbook(request, cars):
queryset = cars
columns = (
'plante_number',
'make',
'model',
'year')
workbook = queryset_to_workbook(queryset, columns)
response = HttpResponse(mimetype='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename="export.xls"'
workbook.save(response)
return response
老实说,我不知道该怎么做才能导出模板。
i在我的模板中有此按钮<输入type = submit name = excel value =导出到Excel />
当我使用它时,我得到:
and to be honest I don't know what to do in template to export it.
i have this button in my template <input type="submit" name="excel" value="Export to Excel" />
and when I use it i get:
TypeError at /
__init__() got an unexpected keyword argument 'mimetype'
Request Method: GET
Request URL: http://127.0.0.1:8000/?search=&excel=Export+to+Excel
Django Version: 1.7.1
Exception Type: TypeError
Exception Value:
__init__() got an unexpected keyword argument 'mimetype'
Exception Location: C:\Python34\lib\site-packages\django\http\response.py in __init__, line 318
Python Executable: C:\Python34\python.exe
Python Version: 3.4.2
如何解决此错误?
请给我一些建议。
谢谢
How can I fix this error? Please, give me some advice. Thanks
推荐答案
将 mimetype
传递给 HttpResponse
在Django 1.7中已弃用并删除
Passing mimetype
to HttpResponse
is deprecated and removed in Django 1.7
您必须使用 content_type
这篇关于如何将Django 1.7中的queryset导出到xls文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!