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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章