小编典典

XlsxWriter对象另存为http响应以在Django中创建下载

django

XlsxWriter对象另存为http响应以在Django中创建下载?


阅读 505

收藏
2020-03-30

共1个答案

小编典典

我想你是在询问如何使用创建内存中的excel文件xlsxwriter并通过返回HttpResponse。这是一个例子:

try:
    import cStringIO as StringIO
except ImportError:
    import StringIO

from django.http import HttpResponse

from xlsxwriter.workbook import Workbook


def your_view(request):
    # your view logic here

    # create a workbook in memory
    output = StringIO.StringIO()

    book = Workbook(output)
    sheet = book.add_worksheet('test')       
    sheet.write(0, 0, 'Hello, world!')
    book.close()

    # construct response
    output.seek(0)
    response = HttpResponse(output.read(), mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
    response['Content-Disposition'] = "attachment; filename=test.xlsx"

    return response

希望能有所帮助。

2020-03-30