from __future__ import absolute_import
import csv
import codecs
import cStringIO
class Echo(object):
def write(self, value):
return value
class UnicodeWriter:
"""
A CSV writer which will write rows to CSV file "f",
which is encoded in the given encoding.
"""
def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
# Redirect output to a queue
self.queue = cStringIO.StringIO()
self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
self.stream = f
self.encoder = codecs.getincrementalencoder(encoding)()
def writerow(self, row):
self.writer.writerow([handle_column(s) for s in row])
# Fetch UTF-8 output from the queue ...
data = self.queue.getvalue()
data = data.decode("utf-8")
# ... and reencode it into the target encoding
data = self.encoder.encode(data)
# write to the target stream
value = self.stream.write(data)
# empty queue
self.queue.truncate(0)
return value
def writerows(self, rows):
for row in rows:
self.writerow(row)
from django.views.generic import View
from django.http.response import StreamingHttpResponse
class ExampleView(View):
headers=['一些','表头']
def get(self,request):
result = [['第一行','数据1'],
['第二行','数据2']]
echoer = Echo()
writer = UnicodeWriter(echoer)
def csv_itertor():
yield codecs.BOM_UTF8
yield writer.writerow(self.headers)
for column in result:
yield writer.writerow(column)
response = StreamingHttpResponse(
(row for row in csv_itertor()),
content_type="text/csv;charset=utf-8")
response['Content-Disposition'
] = 'attachment;filename="example.csv"'
return response
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有