Django创建包含Unicode的CSV文件,可以直接使用Excel打开 [英] Django create CSV file that contains Unicode and can be opened directly with Excel

查看:216
本文介绍了Django创建包含Unicode的CSV文件,可以直接使用Excel打开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过Django创建一个包含unicode数据(希腊字符)的CSV文件,并且我希望它可以从MS Excel直接打开。在其他地方我读过关于unicodecsv库,我决定使用它。所以,这里是我的看法;

 
def get_csv(request,id):
response = HttpResponse(mimetype ='text / csv ')
response ['Content-Disposition'] ='attach; filename = csv.csv'
writer = unicodecsv.writer(response,encoding ='utf-16')
writer.writerow(['Second row','A','B'现在,除了utf-16之外,我还有一个特殊的例子:真的尝试了写入器编码参数中的一切,包括utf-8,utf-8-sig,utf-8-le,utf-16-le和其他。与



Notepad ++可以毫无问题地打开文件,我做错了什么?



更新:这是我在jd的回答后尝试的:

 
import csv
= HttpResponse(mimetype ='text / csv')
response ['Content-Disposition'] ='attachment; filename = test.csv'
response.write(u'\\\'.encode 'utf8'))
writer = csv.writer(response,delimiter =';',dialect ='excel')
writer.writerow(['Second row','A','B' ,'C','Testing',ελληνικά])
返回响应

也可以看到BOM(作为grabage)在Excel - 我也尝试使用unicodecsv和一些其他选项,但再次nothign工作:(



更新2:
我在dda的建议之后尝试过:

 
writer = unicodecsv.writer(response,delimiter =';',dialect ='excel')
writer.writerow(codecs.BOM_UTF16_LE)
writer.writerow([(u'ελληνικά')。decode('utf8')。encode('utf_16_le')])

仍然没有运气:(这里是我得到的错误:

 
UnicodeEncodeError at / csv / 559
'ascii'编解码器不能编码位置0-7中的字符:序数不在范围内(128)

更新3:
我会疯了。为什么这么难?这里是另一个尝试:

 
response.write(codecs.BOM_UTF16_LE)
writer = unicodecsv.writer(response,delimiter ='; ',lineterminator ='\\\
',dialect ='excel',)
writer.writerow('ελληνικ')
writer.writerow(['ελληνικά' .encode('utf_16_le')])#A
writer.writerow(['ελληνικά2')。decode('utf8').coding('utf_16_le'), ').encode('utf_16_le')])#B

这里是Excel的内容:

 
㯎㮵㯎㮻㯎㯎㮹㯎઺ελληνικά딊묃묃뜃봃뤃먃갃㈃딻묃묃뜃봃뤃먃갃㈃

所以我得到了一些希腊字符与#A线。但线B,这是exaclty相同没有产生我希腊字符$ ^#$#^ $#$#^ @@%$#^#^ $#$ Pls hlep!

解决方案

使用Python的 csv 模块,可以编写UTF-8

 使用open('myfile.csv')文件将Excel文件正确读取。 ,'wb')as f:
f.write(u'\\\'.encode('utf8'))
writer = csv.writer(f,delimiter =';',lineterminator = '\\\
',quoting = csv.QUOTE_ALL,dialect ='excel')
...


$ b b

这同样适用于 unicodecsv 。我想你可以直接写BOM直接到 HttpResponse 对象,如果不是你可以使用 StringIO 首先写你的文件



下面是一些编写UTF-8的示例代码带非ASCII字符的CSV文件。我把Django从简单的方程。我可以在Excel中读取该文件。

 # -  *  - 编码:utf-8  -  *  -  
import csv
import os
response = open(os.path.expanduser('〜/ utf8_test.csv'),'wb')
response.write(u'\\\'.encode 'utf8'))
writer = csv.writer(response,delimiter =';',dialect ='excel')
writer.writerow(['Second row','A','B' ,'C','Testing',uελληνικά.encode('utf8')])
response.close()


I want to create a CSV file through Django that contains unicode data (greek characters) and I want it to be opened directly from MS Excel. Elsewhere I had read about the unicodecsv library and I decided to use that. So, here's my view;

def get_csv(request, id):
    response = HttpResponse(mimetype='text/csv')
    response['Content-Disposition'] = 'attachment; filename=csv.csv'
    writer = unicodecsv.writer(response, encoding='utf-16"')
    writer.writerow(['Second row', 'A', 'B', 'C', '"Testing"', "ελληνικά"])
    return response

Now, except utf-16, I had really tried everything in the encoding parameter of the writer, including utf-8, utf-8-sig, utf-8-le, utf-16-le and maybe others. Everytime I opened the file with excel I always saw garbage where the greek characters should've been.

Notepad++ was able to open the file without problems. What am I doing wrong ?

Update: Here's what I tried after jd's answer:

import csv
response = HttpResponse(mimetype='text/csv')
response['Content-Disposition'] = 'attachment; filename=test.csv'
response.write(u'\ufeff'.encode('utf8'))
writer = csv.writer(response, delimiter=';' , dialect='excel')
writer.writerow(['Second row', 'A', 'B', 'C', '"Testing"', "ελληνικά"])
return response

Still no luck - now I also can see the BOM (as grabage) in Excel - I also tried using unicodecsv and some other options but once again nothign worked :(

Update 2: I tried this after dda's proposal:

writer = unicodecsv.writer(response, delimiter=';' , dialect='excel')
writer.writerow(codecs.BOM_UTF16_LE)
writer.writerow([ (u'ελληνικά').decode('utf8').encode('utf_16_le')])

Still no luck :( Here's the error I get:

UnicodeEncodeError at /csv/559
'ascii' codec can't encode characters in position 0-7: ordinal not in range(128)

Update 3: I am going crazy. Why is it so difficult ??? Here's another try:

response.write(codecs.BOM_UTF16_LE)
writer = unicodecsv.writer(response, delimiter=';' ,  lineterminator='\n', dialect='excel',  )
writer.writerow('ελληνικ')
writer.writerow([ ('ελληνικά').decode('utf8').encode('utf_16_le')]) #A
writer.writerow([ ('ελληνικά2').decode('utf8').encode('utf_16_le'),  ('ελληνικά2').decode('utf8').encode('utf_16_le') ]) #B

and here's the contents of the Excel:

㯎㮵㯎㮻㯎㮻㯎㮷㯎㮽㯎㮹㯎઺ελληνικά딊묃묃뜃봃뤃먃갃㈃딻묃묃뜃봃뤃먃갃㈃

So I got some greek characters with the line #A. But line B, which is exaclty the same didn't produce me greek characters $^#$#^$#$#^ @@%$#^#^$#$ Pls hlep !

解决方案

With Python's csv module, you can write a UTF-8 file that Excel will read correctly if you place a BOM at the beginning of the file.

with open('myfile.csv', 'wb') as f:
    f.write(u'\ufeff'.encode('utf8'))
    writer = csv.writer(f, delimiter=';', lineterminator='\n', quoting=csv.QUOTE_ALL, dialect='excel')
    ...

The same should work with unicodecsv. I suppose you can write the BOM directly to the HttpResponse object, if not you can use StringIO to first write your file.

Edit:

Here's some sample code that writes a UTF-8 CSV file with non-ASCII characters. I'm taking Django out of the equation for simplicity. I can read that file in Excel.

# -*- coding: utf-8 -*-
import csv
import os
response = open(os.path.expanduser('~/utf8_test.csv'), 'wb')
response.write(u'\ufeff'.encode('utf8'))
writer = csv.writer(response, delimiter=';' , dialect='excel')
writer.writerow(['Second row', 'A', 'B', 'C', '"Testing"', u"ελληνικά".encode('utf8')])
response.close()

这篇关于Django创建包含Unicode的CSV文件,可以直接使用Excel打开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆