使用 Django 输出 CSV 时出错?
Errror in outputting CSV with Django?
我正在尝试将我的模型输出为 CSV file.It 在模型中处理小数据时工作正常,但处理大数据时速度非常慢 data.And 其次,在将模型输出为时出现一些错误CSV.My 我使用的逻辑是:
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' codec can't encode characters in position 0-6: ordinal not in
range(128)
进一步说:-
The string that could not be encoded/decoded was: عبدالله الحذ
从错误来看,csv文件写入的内容像ASCII字符。所以解码字符。
>>>u'aあä'.encode('ascii', 'ignore')
'a'
可以通过忽略 ASCII 字符修复此错误:
writer.writerow([item.userId.name.encode('ascii', 'ignore')])
替换行
writer.writerow([item.userId.name])
与:
writer.writerow([item.userId.name.encode('utf-8')])
在将 unicode 字符串保存到文件之前,您必须以某种编码对其进行编码。大多数系统默认使用utf-8
,所以这是一个安全的选择。
我正在尝试将我的模型输出为 CSV file.It 在模型中处理小数据时工作正常,但处理大数据时速度非常慢 data.And 其次,在将模型输出为时出现一些错误CSV.My 我使用的逻辑是:
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' codec can't encode characters in position 0-6: ordinal not in range(128)
进一步说:-
The string that could not be encoded/decoded was: عبدالله الحذ
从错误来看,csv文件写入的内容像ASCII字符。所以解码字符。
>>>u'aあä'.encode('ascii', 'ignore')
'a'
可以通过忽略 ASCII 字符修复此错误:
writer.writerow([item.userId.name.encode('ascii', 'ignore')])
替换行
writer.writerow([item.userId.name])
与:
writer.writerow([item.userId.name.encode('utf-8')])
在将 unicode 字符串保存到文件之前,您必须以某种编码对其进行编码。大多数系统默认使用utf-8
,所以这是一个安全的选择。