django 完成excel文件下载,完整例子

来源:互联网 发布:京东好还是淘宝好 编辑:程序博客网 时间:2024/06/05 02:31

从后端开始:

1、配置url

url('^download',downloadTest)

download就是请求的地址,downloadTest是视图方法需要后面实现

  2、编写视图方法downloadTest

from django.http import StreamingHttpResponsedef downloadTest(request):    def file_iterator(file_name, chunk_size=512):#用于形成二进制数据        with open(file_name,'rb') as f:            while True:                c = f.read(chunk_size)                if c:                    yield c                else:                    break    the_file_name ="D:\test.xls"#要下载的文件路径    response =StreamingHttpResponse(file_iterator(the_file_name))#这里创建返回    response['Content-Type'] = 'application/vnd.ms-excel'#注意格式     response['Content-Disposition'] = 'attachment;filename="模板.xls"'#注意filename 这个是下载后的名字    return response#这里选用了StreamingHttpResponse返回,还有其他的方式,请查看下面的urlhttp://www.jianshu.com/p/2ce715671340
================================================================================================================================

前端:

1、在你的页面中增加

<a href="/downloadTest" id="getDownLoad">点击下载</a>
    2、这样点击就会下载了
 如果是个下载按钮的话,可以这样:
    1、添加<a href="/downloadTest" id="getDownLoad"></a>
    2、给按钮绑定单击事件,事件内容就是触发 a 标签点击,也可以完成下载

原创粉丝点击