Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

python - django excel xlwt

On a django site, I want to generate an excel file based on some data in the database.

I'm thinking of using xlwt, but it only has a method to save the data to a file. How can get the file to the HttpResponse object? Or maybe do you know a better library?

I've also found this snippet but it doesn't do what I need. All I want is a way to get the stream from the xlwt object to the response object (without writing to a temporary file)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

neat package! i didn't know about this

According to the doc, the save(filename_or_stream) method takes either a filename to save on, or a file-like stream to write on.

And a Django response object happens to be a file-like stream! so just do xls.save(response). Look the Django docs about generating PDFs with ReportLab to see a similar situation.

edit: (adapted from ShawnMilo's comment):

def xls_to_response(xls, fname):
    response = HttpResponse(mimetype="application/ms-excel")
    response['Content-Disposition'] = 'attachment; filename=%s' % fname
    xls.save(response)
    return response

then, from your view function, just create the xls object and finish with

return xls_to_response(xls,'foo.xls')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...