Преобразование готового рабочего листа в io.BytesIO

Согласно документации xlsxwriter https://xlsxwriter.readthedocs.io/example_django_simple.html, я могу создавать и записывать excel-файлы в django HttpResponse следующим образом:

    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

но я хочу сделать код более многоразовым и тестируемым, поэтому я намерен разбить эту функцию на 3:

def create_worksheet(..) -> xlsxwriter.worksheet.Worksheet
    pass

def convert_worksheet_into_io(worksheet: xlsxwriter.worksheet.Worksheet) -> io.BytesIO:
    pass

def bytesio_to_response(output: io.BytesIO, filename) -> django.http.HttpResponse:
    response = HttpResponse(
        output,
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    )
    response['Content-Disposition'] = f'attachment; filename="{filename}.xlsx"'
    return response

Но я не могу найти, как преобразовать готовый рабочий лист в io.BytesIO. Можете ли вы помочь мне с convert_worksheet_into_io?

Вернуться на верх