Home » excel » python – Stream a huge Excel file, creating it on the fly?

python – Stream a huge Excel file, creating it on the fly?

Posted by: admin April 23, 2020 Leave a comment


I’m writing a web application that might sometimes output dozens of thousands of rows (or even more) in an Excel file. openpyxl was chosen for Excel output preparation, but I’m not sure if I could read the data from the database and output it at the same time. Is there a way to do that? Here’s an example of what I mean in CSV:

def csv_view(request, iterator, keys):
    """A view that streams a large CSV file."""

    class Echo(object):
        """An object that implements just the write method of the file-like
        def write(self, value):
            """Write the value by returning it,
               instead of storing in a buffer."""
            return value

    def get_iter():

        writer = csv.writer(Echo())
        yield writer.writerow(keys)
        for row in iterator:
            yield writer.writerow(row)

    response = StreamingHttpResponse(get_iter(), content_type="text/csv")
    response['Content-Disposition'] = 'attachment; filename="output.csv"'
    return response
How to&Answers:

openpyxl already provides a write-only mode designed for streaming use. However, as all XSLX files are actually zip files and, as the zip format does not allow streaming, it is not possible to stream XLSX files while they are being written.