本文实例讲述了django框架基于模板 生成 excel(xls) 文件操作。分享给大家供大家参考,具体如下:
生成Excel 文件,很多人会采用一些开源的库来实现,比如python 自带 csv 库可以生成类似Excel 一样的东西,当然还有一些专门处理 excel 的库,我以前也有用过,比如这里: //www.jb51.net/article/163408.htm 我介绍过用第三方的库来实现。但事实上还有另外一种办法,采用模板的方法.
虽然标题写的是利用 django 模板来实现,其实并一定,你可以是自定义的一个文本文件。只是这个文件需要满足一定的格式去编写. 是个 xml 格式的,我在自己的项目中写了几个tag, 自己可以去掉后测试:
模板内容
{% load languageTag %}
{% load mulTag%}
<?xml version="1.0"?>
<?mso-application progid="Excel.Sheet"?>
xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:html="http://www.w3.org/TR/REC-html40">
wh
wuhf
2011-05-10T03:11:52Z
2011-05-11T03:09:09Z
ig
11.9999
10290
21600
0
285
False
False
x:FullRows="1" ss:DefaultColumnWidth="54" ss:DefaultRowHeight="14.25">
{%if filter.phase == 'week'%}{%padLang 3_week_report%} {%else%} {%padLang 3_month_report%} {%endif%}
{%padLang 3_pay_date%} : {{filter.start_date}} - {{filter.end_date}}
{%padLang 3_order_info%}
{%padLang 3_pay_info%}
{%padLang 3_order_sn%}
{%padLang 3_user_name%}
{%padLang 3_distributor_name%}
{%padLang 3_amount%}
{%padLang 3_amount_source%}
{%padLang 3_create_date%}
{%padLang 3_installment%}
{%padLang 3_pay_name%}
{%padLang 3_amount_local%}
{%padLang 3_amount_amr%}
{%padLang 3_pay_date%}
{%for phase,orders in res.iteritems%}
{%for order_sn,order_pays in orders.iteritems%}
{%for item in order_pays%}
{%if forloop.first %}
{{item.order_sn}}
{{item.user_name}}
{{item.distributor_name}}
{{item.order_subtotal}}
{%if item.order_subtotal == 1%} {%padLang 3_user%}{%else%}{%padLang 3_distributor%}{%endif%}
{%if item.create_date == 0 %}{{item.pay_date.}}{%else%} {{item.create_date}} {%endif%}
{%if item.installment_id%} {%padLang 3_yes%}{%else%} {%padLang 3_no%}{%endif%}';
{%else%}
{%endif%}
{%if item.payment_id == '-2'%}{%padLang 3_amount_hand%}
{%else%}{%if item.payment_id == '0'%} {%else%}{{item.pay_name}}{%endif%}
{%endif%}
{{item.pay_money}} {{item.rate_name}}
{{item.amr}}
{{item.pay_date}}
{%endfor%}
{%endfor%}
{%padLang 3_subtotal%}
{{item.phase_subtotal}}
{%endfor%}
{%padLang 3_total%}
ss:Type="Number">{{total}}
这段模板里面包含了一些我自己的逻辑,熟悉 django 的人一眼就能看出来,那些是我加的,那些是原来应该有的,其实道理就是,循环处理 和 把数据向里面填充就可以了。
在视图中如何处理呢:
def report_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)
return response
这样就可以实现直接用 Django 渲染模板下载 excel 文档了。还是很方便的,至少不用调用很多三方的API函数去生成excel.
希望本文所述对大家基于Django框架的Python程序设计有所帮助。
本文标题: django框架基于模板 生成 excel(xls) 文件操作示例
本文地址: http://www.cppcns.com/jiaoben/python/262660.html