pythonexcelbrowsercgiopenpyxl

how to output xlsx generated by Openpyxl to browser?


I was using stackoverflow for a while now and it helped me very often. Now I have a problem I couldn't solve myself or through searching. I'm trying to output my excel file generated by openpyxl in browser as I was doing it with phpexcel. The method appears to be the same, but I only get broken file. My code looks like this:

from openpyxl.workbook import Workbook
from openpyxl.writer.excel import ExcelWriter
from openpyxl.writer.excel import save_virtual_workbook
from openpyxl.cell import get_column_letter
from StringIO import StringIO

print 'Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
print 'Content-Disposition: attachment;filename="results.xlsx"'
print 'Cache-Control: max-age=0\n'

output = StringIO()

wb = Workbook()

ws = wb.worksheets[0]

ws.cell('A1').value = 3.14

wb.save(output)
print output.getvalue()
#print save_virtual_workbook(wb)

I use the version 1.5.8 and python 2.7. None of the approaches works. When I just use it from desktop and not browser it works flawlessly. I would be very thankful for help.

P.S. please don't tell me that using other language or program would be easier. I need to solve this with python.


Solution

  • Writing the xlsx output to disk and then serving it up via Apache worked perfectly, but putting it out directly caused errors in Excel and other issues.

    I added a couple of extra steps and made one minor change to your code:

    buffer=output.getvalue()
    

    In the HTTP headers:

    print "Content-Length: " + str(len(buffer))
    

    And used write() instead of print() to push the buffer into the standard output stream:

    stdout.write(buffer)