0 0

django 导出csv excel乱码3

系统是ubuntu

#-*- coding: UTF-8 -*- 
import csv
w = csv.writer(open('output.csv','w'))
a = '不'
a = a.encode('utf8')
w.writerow(a)



报错:UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128)

2
#-*- coding: UTF-8 -*- 
import csv
w = csv.writer(open('output.csv','w'))
w.write('\xEF\xBB\xBF')
w.writerow([0, '不', 2, 3, 4, 5, 6, 7, 8, 9])

报错:AttributeError: '_csv.writer' object has no attribute 'write'

3.Django


解决方法:在csv文件的最开头,添加UTF-8的BOM标记即可。(在Django中应该是在response的最开头写入BOM标记)


    # Create the HttpResponse object with the appropriate CSV header.
    response = HttpResponse(mimetype='text/csv')
    response.write('\xEF\xBB\xBF')
    response['Content-Disposition'] = 'attachment; filename=somefilename.csv'



我用openoffice打开没有问题,excel打开还是乱码。

4.Django

def hello(request):  
    response = HttpResponse(mimetype='text/csv')
    response.write('\xEF\xBB\xBF')
    response['Content-Disposition'] = 'attachment; filename=somefilename.csv'
    writer = csv.writer(response)
    writer.writerow(['s'])
    q = u'不'
    q = q.encode('utf8')
    writer.writerow([q])
    return response


报错:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128)

到底怎么办?


搞定了!!!!
在python2.7 版本以下,先把二进制文件写进去在用csv:

#-*- coding: UTF-8 -*-  
import csv
import codecs

fobj = open('output4.csv','wb')
fobj.write(codecs.BOM_UTF8)
w = csv.writer(fobj)
a = u'不' 
a = a.encode('utf8')
w.writerow([a])
fobj.close()


在python2.7中好像有
DictWriter.writeheader()¶

    Write a row with the field names (as specified in the constructor).

    New in version 2.7.
不知可不可以。


2010年12月31日 17:15
目前还没有答案

相关推荐

Global site tag (gtag.js) - Google Analytics