django excel xlwt [英] django excel xlwt

查看:139
本文介绍了django excel xlwt的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在django网站上,我想根据数据库中的某些数据生成一个excel文件。

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

我正在考虑使用 xlwt ,但它只有一种将数据保存到文件的方法。如何获取文件到HttpResponse对象?或者也许你知道一个更好的图书馆?

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?

我也发现这个片段,但它不会做我所需要的。所有我想要的是将流从xlwt对象到响应对象(不写入临时文件)的方式。

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)

推荐答案

整齐的包!我不知道这个

neat package! i didn't know about this

根据该文档, save(filename_or_stream)方法采用文件名保存,或类似文件的流写入。

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.

Django响应对象恰好是一个类似文件的流!所以只要做 xls.save(response)。查看Django文档关于生成PDF 与ReportLab的文档看到类似的情况。

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.

编辑:(改编自ShawnMilo的评论):

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

然后,从您的视图函数,只需创建 xls 对象,并使用

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

return xls_to_response(xls,'foo.xls')

这篇关于django excel xlwt的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆