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

ohfgkhjo  于 2022-12-25  发布在  Python
关注(0)|答案(6)|浏览(147)

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

kyxcudwk

kyxcudwk1#

对Python 3的@alecxe响应(io. BytesIO而不是StringIO. StringIO)和Django〉= 1.5(content_type而不是mimetype)进行了一点更新,使用了完全在内存中的文件汇编,该文件汇编已经由@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
jslywgbw

jslywgbw2#

我想你问的是如何使用xlsxwriter在内存中创建一个excel文件,并通过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
gmol1639

gmol16393#

说到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()

jhkqcmku

jhkqcmku4#

最好遵循jmcnamara(软件包开发商)的官方文档
Example: Simple Django class

7lrncoxx

7lrncoxx5#

我在reportProgress: True中使用nodejs,我的Django代码是这样的;

output = io.BytesIO()
workbook = xlsxwriter.Workbook(output, {'in_memory': True})
worksheet = workbook.add_worksheet()

worksheet.write(y, x, column_name)
worksheet.write(y, x, column_name)

workbook.close()
output.seek(0)
return FileResponse(output.read(), filename="reservations.xlsx")

如果你这样做,你就可以像这样

mefy6pfw

mefy6pfw6#

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

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

相关问题