django框架基于模板 生成 excel(xls) 文件操作示例
本文实例讲述了django框架基于模板生成excel(xls)文件操作。分享给大家供大家参考,具体如下:
生成Excel文件,很多人会采用一些开源的库来实现,比如python自带csv库可以生成类似Excel 一样的东西,当然还有一些专门处理excel的库,我以前也有用过,比如这里://www.nhooo.com/article/163408.htm我介绍过用第三方的库来实现。但事实上还有另外一种办法,采用模板的方法.
虽然标题写的是利用django模板来实现,其实并一定,你可以是自定义的一个文本文件。只是这个文件需要满足一定的格式去编写.是个xml格式的,我在自己的项目中写了几个tag,自己可以去掉后测试:
模板内容
{%loadlanguageTag%}
{%loadmulTag%}
wh
wuhf
2011-05-10T03:11:52Z
2011-05-11T03:09:09Z
ig
11.9999
10290
21600
0
285
False
False
{%iffilter.phase=='week'%}{%padLang3_week_report%}{%else%}{%padLang3_month_report%}{%endif%}
{%padLang3_pay_date%}:{{filter.start_date}}-{{filter.end_date}}
{%padLang3_order_info%}
{%padLang3_pay_info%}
{%padLang3_order_sn%} |
{%padLang3_user_name%} |
{%padLang3_distributor_name%} |
{%padLang3_amount%} |
{%padLang3_amount_source%} |
{%padLang3_create_date%} |
{%padLang3_installment%} |
{%padLang3_pay_name%} |
{%padLang3_amount_local%} |
{%padLang3_amount_amr%} |
{%padLang3_pay_date%} |
{%forphase,ordersinres.iteritems%}
{%fororder_sn,order_paysinorders.iteritems%}
{%foriteminorder_pays%}
{%ifforloop.first%}
{{item.order_sn}} |
{{item.user_name}} |
{{item.distributor_name}} |
{{item.order_subtotal}}
{%ifitem.order_subtotal==1%}{%padLang3_user%}{%else%}{%padLang3_distributor%}{%endif%} |
{%ifitem.create_date==0%}{{item.pay_date.}}{%else%}{{item.create_date}}{%endif%}
{%ifitem.installment_id%}{%padLang3_yes%}{%else%}{%padLang3_no%}{%endif%} | ';
{%else%}
|
|
|
|
|
|
{%endif%}
{%ifitem.payment_id=='-2'%}{%padLang3_amount_hand%}
{%else%}{%ifitem.payment_id=='0'%}{%else%}{{item.pay_name}}{%endif%}
{%endif%}
|
{{item.pay_money}}{{item.rate_name}}
{{item.amr}}
{{item.pay_date}}
{%endfor%}
{%endfor%}
{%padLang3_subtotal%}
{{item.phase_subtotal}}
{%endfor%}
{%padLang3_total%} |
{{total}}
这段模板里面包含了一些我自己的逻辑,熟悉django的人一眼就能看出来,那些是我加的,那些是原来应该有的,其实道理就是,循环处理
在视图中如何处理呢:
defreport_pad_order(request): .... t=TemplateResponse(request,'pad_order_report_xls.html',context) t.render() response=HttpResponse(content_type='application/vnd.ms-excel') response['Content-Disposition']='attachment;filename=test.xls' response.write(t.content) returnresponse
这样就可以实现直接用Django渲染模板下载excel文档了。还是很方便的,至少不用调用很多三方的API函数去生成excel.
希望本文所述对大家基于Django框架的Python程序设计有所帮助。