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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014686399/article/details/78198306

从后端开始:

1、配置url

url('^download',downloadTest)

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

  2、编写视图方法downloadTest

from django.http import StreamingHttpResponse
def 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返回,还有其他的方式,请查看下面的url
http://www.jianshu.com/p/2ce715671340
================================================================================================================================

前端:

1、在你的页面中增加

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

猜你喜欢

转载自blog.csdn.net/u014686399/article/details/78198306
今日推荐