gpt4 book ai didi

python - Django:导出我内存中的excel文件

转载 作者:太空宇宙 更新时间:2023-11-03 16:41:32 26 4
gpt4 key购买 nike

我想导出内存中的一些 Excel 文件,这是我的代码。

wrapper = open('/home/filename.xlsx')
response = HttpResponse(wrapper,content_type='application/force-download')
response['Content-Disposition'] = 'attachment ; filename=%s' % smart_str('filename.xlsx')
response['X-Sendfile'] = smart_str('/home/filename.xlsx')
return response

当我使用Python 2.7时没有问题,但如果我使用Python 3.5则会出现错误

'utf-8' codec can't decode byte 0x9c in position 10:invalid start byte 

我猜错误是因为它们的差异(开放功能)

打开内存中的 Excel 文件并将其导出的正确方法是什么?

最佳答案

在 Python 3.x 中,文件默认以文本模式打开。将第一行更改为:

wrapper = open('/home/filename.xlsx', 'rb')

来自Python 3 documentation (强调我的):

Normally, files are opened in text mode, that means, you read and write strings from and to the file, which are encoded in a specific encoding. If encoding is not specified, the default is platform dependent (see open()). 'b' appended to the mode opens the file in binary mode: now the data is read and written in the form of bytes objects. This mode should be used for all files that don’t contain text.

关于python - Django:导出我内存中的excel文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36733737/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com