Django2.1实现Excel下载功能

Django2.1实现Excel下载功能

  • 使用HttpResponse
  • 使用FileResponse
  • 使用StreamingHttpResponse

使用HttpResponse

对于文本类型的文件,在传输过程中往往会发生一点点意想不到的效果。
为了保证文件的完整性,我推荐对于Excel等类型的文本文件使用HttpResponse进行传送

    filename = 'xxxxxxx.xlsx'
    with open(file_path, 'rb') as f:
        f_byte = f.read()
    response = HttpResponse(f_byte)
    response['Content-Type'] = 'application/octet-stream'
    response['Content-Disposition'] = 'attachment;filename="{0}"'.format(filename)
    return response

使用FileResponse

from django.http import FileResponse

with open(file_path, 'rb') as f:
        f_byte = f.read()
response = FileResponse(f_byte)
response['Content-Type'] = 'application/octet-stream'
response['Content-Disposition'] = 'attachment;filename="{0}"'.format(filename)
return response

使用StreamingHttpResponse

from django.http import StreamingHttpResponse

    def file_iterator(file_path, chunk_size=512):
        with open(file_path, 'rb') as f:
            while True:
                c = f.read(chunk_size)
                if c:
                    yield c
                else:
                    break
response = StreamingHttpResponse(file_iterator(file_path))
response['Content-Type'] = 'application/octet-stream'
response['Content-Disposition'] = 'attachment;filename="{0}"'.format(filename)
return response

你可能感兴趣的:(Django,Python进阶,web框架,Django2.1,Python)