Python Django将模型下载为Excel文件

时间:2016-08-21 23:33:24

标签: python django django-models

我有一些包含一些数据的数据库,我想将它作为excel文件下载。换句话说,当我点击我的应用程序上的下载按钮时,如何以编程方式将我的模型转换为excel文件?

1 个答案:

答案 0 :(得分:2)

使用优秀的xlsxwriter库。我用它来自django,非常棒 容易。

from django.http import HttpResponse
import xlsxwriter

def returnexcel():
    response = HttpResponse(content_type='application/vnd.ms-excel')
    response['Content-Disposition'] = 'attachment; filename="mymodel.xlsx"'

    workbook = xlsxwriter.Workbook(response, {'in_memory': True})

# add a worksheet

    worksheet = workbook.add_worksheet()
    worksheet.write_... 

# use xlsxwriter routines to create the worksheet

# now write it out
    workbook.close()
    return response

http://xlsxwriter.readthedocs.io/index.html