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
posted @ 2020-06-17 16:29  zju_cxl  阅读(271)  评论(0)    收藏  举报