Django導出excel中文亂碼解決方案


Django官方文檔有關於怎么生成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"' 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里寫入BOM  response.write(codecs.BOM_UTF8)

import csv,codecs 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.write(codecs.BOM_UTF8)
    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

*****************************

 

附上非Django情況下csv亂碼問題

python2中:

  1. import csv,codecs  
  2. f=open('temp.csv','w')  
  3. f.write(codecs.BOM_UTF8)  
  4. writer = csv.writer(f)  
  5. writer.writerow(['奧迪','豆豆','方法'])  
  6. f.close()  

 

python3中:

 
  1. import csv,codecs  
  2. f = codecs.open('temp.csv', 'w', 'utf_8_sig')  
  3. writer = csv.writer(f)  
  4. writer.writerow(['奧迪','愛迪生','方法'])  
  5. f.close()  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM