【问题标题】:Errror in outputting CSV with Django?使用 Django 输出 CSV 时出错?
【发布时间】:2017-05-12 09:11:36
【问题描述】:

我正在尝试将我的模型输出为 CSV 文件。它适用于模型中的小数据,但处理大数据时速度非常慢。其次,将模型输出为 CSV 时出现一些错误。我的逻辑是我我使用的是:

def some_view(request):
    # Create the HttpResponse object with the appropriate CSV header.
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="news.csv"'
    writer = csv.writer(response)
    news_obj = News.objects.using('cms').all()
    for item in news_obj:
        #writer.writerow([item.newsText])
        writer.writerow([item.userId.name])

    return response

我面临的错误是:

UnicodeEncodeError :-- “ascii”编解码器无法对位置 0-6 中的字符进行编码:序数不在 范围(128)

它还说:-

无法编码/解码的字符串是:عبداله الحذ

【问题讨论】:

  • 错误在于您的编码,请在内容配置中传递编码格式,如 UTF-8

标签: python django export-to-csv


【解决方案1】:

换行

writer.writerow([item.userId.name])

与:

writer.writerow([item.userId.name.encode('utf-8')])

在将 unicode 字符串保存到文件之前,您必须以某种编码对其进行编码。大多数系统默认使用utf-8,所以这是一个安全的选择。

【讨论】:

  • 如果你知道先生,它不适用于大文件吗?
  • 什么意思?你收到什么错误?文件有多大?
  • 感谢我使用流式传输大型 CSV 文件实现的关注
【解决方案2】:

从错误中,csv 文件的写入内容类似于 ASCII 字符。所以解码字符。

>>>u'aあä'.encode('ascii', 'ignore')
'a'

可以通过忽略 ASCII 字符来修复此错误:

writer.writerow([item.userId.name.encode('ascii', 'ignore')])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-05
    • 1970-01-01
    • 2017-04-25
    • 1970-01-01
    • 2013-03-03
    • 2013-02-05
    相关资源
    最近更新 更多