41

XlsxWriter object save as http response to create download in Django?

4

5 回答 5

82

对 Python 3( io.BytesIO而不是StringIO.StringIO)和 Django >= 1.5 (content_type而不是mimetype )的@alecxe 响应的一点更新,以及此后由@jmcnamara ({ 'in_memory':真})!
这是完整的示例:

import io

from django.http.response import HttpResponse

from xlsxwriter.workbook import Workbook


def your_view(request):

    output = io.BytesIO()

    workbook = Workbook(output, {'in_memory': True})
    worksheet = workbook.add_worksheet()
    worksheet.write(0, 0, 'Hello, world!')
    workbook.close()

    output.seek(0)

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

    output.close()

    return response
于 2014-12-10T16:20:00.287 回答
63

我想你是在问如何使用在内存中创建一个 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

希望有帮助。

于 2013-05-16T20:19:31.283 回答
20

说到 Django,你甚至可以不用所有的StringIO恶作剧。HttpResponse在这方面表现得就像一个 StringIO :

from django.http import HttpResponse
from xlsxwriter.workbook import Workbook

def your_view(request):
    # your view logic here

    # create the HttpResponse object ...
    response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response['Content-Disposition'] = "attachment; filename=test.xlsx"

    # .. and pass it into the XLSXWriter
    book = Workbook(response, {'in_memory': True})
    sheet = book.add_worksheet('test')       
    sheet.write(0, 0, 'Hello, world!')
    book.close()

    return response

附录:您需要指定{'in_memory': True},否则您可能会得到HttpResponse has no attribute seek(). 谢谢@Jeb

于 2016-04-25T09:41:19.733 回答
1

最好遵循jmcnamara (package developer)的官方文档

示例:简单的 Django 类

于 2021-04-19T15:44:09.023 回答
0

一个简单的 Django View 类,用于使用 XlsxWriter 模块编写 Excel 文件。

import io
from django.http import HttpResponse
from django.views.generic import View
import xlsxwriter


def get_simple_table_data():
    # Simulate a more complex table read.
    return [[1, 2, 3],
            [4, 5, 6],
            [7, 8, 9]]


class MyView(View):

    def get(self, request):

        # Create an in-memory output file for the new workbook.
        output = io.BytesIO()

        # Even though the final file will be in memory the module uses temp
        # files during assembly for efficiency. To avoid this on servers that
        # don't allow temp files, for example the Google APP Engine, set the
        # 'in_memory' Workbook() constructor option as shown in the docs.
        workbook = xlsxwriter.Workbook(output)
        worksheet = workbook.add_worksheet()

        # Get some data to write to the spreadsheet.
        data = get_simple_table_data()

        # Write some test data.
        for row_num, columns in enumerate(data):
            for col_num, cell_data in enumerate(columns):
                worksheet.write(row_num, col_num, cell_data)

        # Close the workbook before sending the data.
        workbook.close()

        # Rewind the buffer.
        output.seek(0)

        # Set up the Http response.
        filename = 'django_simple.xlsx'
        response = HttpResponse(
            output,
            content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        )
        response['Content-Disposition'] = 'attachment; filename=%s' % filename

        return response
于 2021-08-30T08:45:23.367 回答