source

XlsxWriter 개체는 Django에서 다운로드를 생성하기 위해 http 응답으로 저장됩니다.

manycodes 2023. 4. 16. 15:22
반응형

XlsxWriter 개체는 Django에서 다운로드를 생성하기 위해 http 응답으로 저장됩니다.

XlsxWriter 개체를 http 응답으로 저장하여 Django에서 다운로드를 생성하시겠습니까?

Python 3의 @alecxe 응답에 대한 약간의 업데이트(io).문자열아닌 바이트 IOIO. 문자열IO) 및 Django > = 1.5(mimtype 대신 content_type), 이후 @jmcnamara('in_memory'): True )!
다음으로 완전한 예를 제시하겠습니다.

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

메모리에서 엑셀 파일을 만드는 방법을 물어보는 것 같은데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

장고에 관한 한 통이 없어도 된다.StringIO셰나니건스. HttpResponse스트링과 같이 동작합니다.이 점에 있어서 IO:

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님 감사합니다.

jmcnamara(패키지 개발자)의 공식 문서를 따르는 것이 좋습니다.

예: Simple Django

nodejs를 사용하여reportProgress: True제 장고 코드는 이렇습니다.

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")

이렇게 하면 이렇게 쓸 수 있어요.

이미지 로드

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

언급URL : https://stackoverflow.com/questions/16393242/xlsxwriter-object-save-as-http-response-to-create-download-in-django

반응형