1. 程式人生 > >django 生成csv excel 檔名及檔案內容 中文亂碼 解決

django 生成csv excel 檔名及檔案內容 中文亂碼 解決

#attachment表示以檔案形式下載,urlquote解決檔名中文文字亂碼解決
#codecs.BMO_UTF8解決檔案內容中文亂碼
from app1 import models
from django.shortcuts import render,redirect,HttpResponse
import csv,codecs
from django.utils.http import urlquote

def downloadSopCsv(request):
    sops = models.StandardFile.objects.all().order_by("-cusDate").values_list("title","cus__companyName","cusDate","qs__name","files__name")
    response = HttpResponse(content_type="text/csv")
    #attachment表示以檔案形式下載,urlquote解決檔名中文文字亂碼解決
    #codecs.BMO_UTF8解決檔案內容中文亂碼
    response.write(codecs.BOM_UTF8)
    response['Content-Disposition'] = 'attachment;filename="%s"'%(urlquote("raylu.csv"))
    writer = csv.writer(response)
    writer.writerow(["filename","customerCompany","date","createMember","attchmentFile"])
    for sop in sops:
        writer.writerow(sop)
    return response