Python Django导出CSV与日文文本

时间:2015-02-09 09:12:31

标签: python django csv encoding encode

导出CSV问题

#==================================
Python 2.7.6
Django 1.7
#==================================

# Get from MySQL
{'SearchItem_1_JP': u'\u30a2\u30af\u30bb\u30b5\u30ea\u30fc'} # アクセサリー
searchitem_1_jp = searchitem['SearchItem_1_JP']

# Output CSV
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="test_export.csv"'
writer = csv.writer(response)
writer.writerow([searchitem_1_jp.encode('utf8')])
writer.writerow([searchitem_1_jp.encode('U8')])
writer.writerow([searchitem_1_jp.encode('UTF')])
writer.writerow([searchitem_1_jp.encode('utf8')])
writer.writerow([searchitem_1_jp.encode('utf_8_sig')])

writer.writerow([searchitem_1_jp.encode('ascii', 'ignore')])        

writer.writerow([searchitem_1_jp.encode('cp932')])

writer.writerow([searchitem_1_jp.encode('euc_jp')])
writer.writerow([searchitem_1_jp.encode('euc_jis_2004')])
writer.writerow([searchitem_1_jp.encode('euc_jisx0213')])

writer.writerow([searchitem_1_jp.encode('iso2022_jp')])
writer.writerow([searchitem_1_jp.encode('iso2022_jp_1')])
writer.writerow([searchitem_1_jp.encode('iso2022_jp_2')])

writer.writerow([searchitem_1_jp.encode('iso2022_jp_2004')])
writer.writerow([searchitem_1_jp.encode('iso2022_jp_3')])
writer.writerow([searchitem_1_jp.encode('iso2022_jp_ext')])

writer.writerow([searchitem_1_jp.encode('shift_jis')])
writer.writerow([searchitem_1_jp.encode('shift_jis_2004')])
writer.writerow([searchitem_1_jp.encode('shift_jisx0213')])

return response

==================================

我尝试过日语的所有编解码方法。 但是,导出的CSV文件的数据仍然是乱码。

参考:https://docs.python.org/2/library/codecs.html#codec-base-classes

1 个答案:

答案 0 :(得分:0)

Python的内置csv库不符合unicode。您可以尝试直接替换unicodecsv