Django 文件下载,解决excel文件乱码

模板:

<a href="{% url 'Analyse:downFile' %}">国内.xlsx</a>

urls:

path('downFile/', views.download_file, name='downFile'),

视图:

def download_file(request):
    path = os.path.abspath(os.path.dirname(__file__))
    the_file_name = '国内.xlsx'
    filename = path+'/static/COVID_19Analyse/Upload/'+the_file_name
    response = StreamingHttpResponse(readFile(filename))
    response['Content-Type'] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    response['Content-Disposition'] = 'attachment;filename="{0}"'.format(the_file_name)
    return response


def readFile(filename, chunk_size=512):
    with open(filename, 'rb') as f:
        while True:
            c = f.read(chunk_size)
            if c:
                yield c
            else:
                break

要注意文件类型,不同文件的文件类型不一样,我这里文件是xlsx文件,文件类型才是那个东西。

常用office文件对应的文件类型如下:

 

后缀    MIME Type
.doc    application/msword
.docx    application/vnd.openxmlformats-officedocument.wordprocessingml.document
.xls    application/vnd.ms-excel
.xlsx    application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
.ppt    application/vnd.ms-powerpoint
.pps   application/vnd.ms-powerpoint
.pptx   application/vnd.openxmlformats-officedocument.presentationml.presentation
.ppsx    application/vnd.openxmlformats-officedocument.presentationml.slideshow
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值