Django在视图和下载时生成csv文件

时间:2017-01-17 20:48:24

标签: python django csv

我有这段代码:

    with open('stockitems_misuper.csv', 'wb') as myfile:
        wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
        wr.writerows(file_rows)

    response = HttpResponse(myfile, content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename=stockitems_misuper.csv'
    return response

我收到错误:

  

关闭文件的I / O操作

如何将创建的csv文件发送到前端?

1 个答案:

答案 0 :(得分:8)

您正在传递正在写入的文件的句柄(并且不确定您的缩进,您可能只是在with块之外。

只需在阅读模式下重新打开它。

with open('stockitems_misuper.csv', 'w', newline="") as myfile:  # python 2: open('stockitems_misuper.csv', 'wb')
    wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
    wr.writerows(file_rows)

with open('stockitems_misuper.csv') as myfile:
    response = HttpResponse(myfile, content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename=stockitems_misuper.csv'
    return response

或更好:写入io.StringIO()实例,然后传递,避免创建文件。

import io,csv

buffer = io.StringIO()  # python 2 needs io.BytesIO() instead
wr = csv.writer(buffer, quoting=csv.QUOTE_ALL)
wr.writerows(file_rows)

buffer.seek(0)
response = HttpResponse(buffer, content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename=stockitems_misuper.csv'

return response