I'm going crazy here to implement a reporting system for .docx files. I read several examples of streaming a file (like CSV outputs and such), but they were all from the controller. Since there will be several report formats for my application, I wanted to move all the reports to the views. I SWEAR I had it working and then fouled it up somehow.
Here's what works.
controllers/sale.py
@auth.requires_login()
def test5():
from docx import Document
from docx.shared import Inches
import StringIO
output = StringIO.StringIO()
document = Document()
sales = db(db.sale.property==db.property.id).select()
document.add_heading('Sales', 0)
response.headers['Content-Type']='application/vnd.openxmlformats-officedocument.wordprocessingml.document'
response.headers['Content-Disposition'] = "attachment; filename=Comparable Sales.docx"
response.write(output.getvalue(), escape=False)
document.save(output)
return output.getvalue()
It produces a .docx file. No data yet, but just a file with the heading caption that reads, "Sales."
Then, I tried splitting stuff up a bit.
controllers/sale.py
@auth.requires_login()
def test4():
response.view = 'default/test2.html'
return locals()
views/default/test2.html
{{
from docx import Document
from docx.shared import Inches
import StringIO
output = StringIO.StringIO()
document = Document()
sales = db(db.sale.property==db.property.id).select()
document.add_heading('Sales', 0)
response.headers['Content-Type']='application/vnd.openxmlformats-officedocument.wordprocessingml.document'
response.headers['Content-Disposition'] = "attachment; filename=Comparable Sales.docx"
document.save(output)
response.write(output.getvalue(), escape=False)
}}
With the split-up deal, it downloads fine. When I open it, Word alerts me first, "The file Comparable Sales.docx cannot be opened because there are problems with the contents."
I click OK and get:
"Word found unreadable content in Comparable Sales.docx. Do you want to recover the contents of this document?"
I click OK and it opens with the correct content.
I've tried several variations, such as moving the sales query to the controller, removing the Content-Disposition header, etc. No luck.
I've tried comparing the underlying document.xml files, but I don't notice any notable differences. I've validated and checked for errors.
So, clearly I'm very close if it's actually getting the content, but what have I done that keeps making it corrupt?