python - 如何将 Django 1.7 中的查询集导出到 xls 文件?

标签 python django django-templates django-views

我使用 Django 1.7.1 和 Python 3.4。我想将搜索结果导出到 Excel 文件。 我在 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

说实话,我不知道在模板中该怎么做才能导出它。 我的模板中有这个按钮 <input type="submit" name="excel" value="Export to Excel" /> 当我使用它时,我得到:

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

如何修复此错误? 请给我一些建议。 谢谢

最佳答案

mimetype 传递给 HttpResponse 已在 Django 1.7 中弃用并删除

您必须使用content_type

关于python - 如何将 Django 1.7 中的查询集导出到 xls 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29732812/

相关文章:

python - 如何从 python 模块安装 requirements.txt 文件?

python - mpi4py:未加载库:/usr/local/lib/libmpi.1.dylib

python - 如何执行 python 脚本并将输出写入文件?

python - django 1.5 中的 django.utils.thread_support

python - ***在Python -3中是什么意思?

django - 在 Django 中测试 apps.py

python - django-debug-toolbar 安装导致 : No such file or directory: '/var/www/static'

python - Django-限制用户访问url

python - 在 Django 中创建新闻文件

django - 在 Django 1.6 中的模板中全局访问对象