2017-07-03 31 views
0

即時通訊使用python csv庫用於將我的模型導出到django中的csv文件。 代碼是這樣的:Python-Django utf-8 csv.writer

import csv 
from django.http import HttpResponse 

def some_view(request): 
    # Create the HttpResponse object with the appropriate CSV header. 
    response = HttpResponse(content_type='text/csv') 
    response['Content-Disposition'] = 'attachment; filename="somefilename.csv"' 

    writer = csv.writer(response) 
    writer.writerow(['First row', 'Foo', 'Bar', 'Baz']) 
    writer.writerow(['Second row', 'A', 'B', 'C', '"Testing"', "Here's a quote"]) 

    return response 

我的問題: 在我的數據庫我有一些波斯文字,僅僅用UTF-8編碼格式的作品,所以當我在Excel中打開生成CSV文件中的波斯文字不正確顯示。

回答

-1

首先添加:

# coding: utf-8 

在你的.py文件的頂部。其次,這不是Django問題,而是MS Excel問題。上週我有類似的問題,發現在excel中,當你選擇編碼時,你只需要設置語言代碼(或類似的東西)到UTF-8家族而不是波斯語。

+0

如果你打開一個記事本正常.csv文件,你會看到你的信那麼一切都與文件ok'ey。 –

+0

如果字母出現問題,請在包含字母的字段中添加.encode('UTF-8')。 –

0

利用這一點,我有阿拉伯字符,並在某些情況下工作得很好,我

def university_csv(request): 
    response = HttpResponse(content_type='text/csv') 
    response['Content-Disposition'] = 'attachment; filename="university_list.csv"' 
    writer = csv.writer(response) 
    university_obj = Universities.objects.using('cms').all() 
    writer.writerow(['id', 'NAME', 'ABBREVIATION', 'ADDRESS']) 
    for item in university_obj: 
     if item.address: 
      if item.abbreviation: 
       writer.writerow([item.id, item.name.encode('UTF-8'), item.abbreviation.encode('UTF-8'), 
           item.address.encode('UTF-8')]) 
      else: 
       writer.writerow([item.id, item.name.encode('UTF-8'), item.abbreviation, item.address.encode('UTF-8')]) 
     else: 
      if item.abbreviation: 
       writer.writerow([item.id, item.name.encode('UTF-8'), item.abbreviation.encode('UTF-8')]) 
      else: 
       writer.writerow([item.id, item.name.encode('UTF-8')]) 

    return response 
+0

你可以看到utf格式並忽略if else條件。 –

+0

我之前嘗試過,但結果不是一個可讀的字符串它的utf-8文字像\ xd8 \ x80或類似的東西。 – Arash

+0

你可以更新你的代碼 –

0

我嘗試編碼(「UTF-8」)的解決方案,但結果在Microsoft Excel無法讀取,它表明b '\ XD8 \ XB1 \ XDB \ x8c \ XD8'。 但是我發現在Excel中顯示CSV的正確方法是可讀的。

import csv 
from django.http import HttpResponse 

def some_view(request): 
    # Create the HttpResponse object with the appropriate CSV header. 
    response = HttpResponse(content_type='text/csv') 
    response['Content-Disposition'] = 'attachment; filename="somefilename.csv"' 

    response.write(u'\ufeff'.encode('utf8')) 
    writer = csv.writer(response) 
    writer.writerow(['First row', 'Foo', 'Bar', 'Baz']) 
    writer.writerow(['Second row', 'A', 'B', 'C', '"Testing"', "Here's a quote"]) 

    return response 

只需添加的Response.Write(U '\ ufeff'.encode(' utf-8' ))到代碼

+0

我quess你應該嘗試編碼('utf8')在writer.writerrow不響應.write –