Django で Shift-JIS の CSV を出力

投稿者: ytyng 7年, 9ヶ月 前

Python 3, Django 1.9

StringIO に ユニコードで書いちゃってから CP932に一気に変換するのがトラブル少なくてわかりやすいかなと思います。

class CSVView(View):
def get(self, request, **kwargs):

response = HttpResponse(content_type='text/csv; charset=Shift-JIS')
response['Content-Disposition'] = \
'attachment; filename=items.csv'
sio = io.StringIO()
writer = csv.writer(sio)
writer.writerow(self.header)
for row in self.get_rows():
writer.writerow(row)
response.write(sio.getvalue().encode('cp932'))
return response
現在の評価: 4.1

コメント

アーカイブ

2024
2023
2022
2021
2020
2019
2018
2017
2016
2015
2014
2013
2012
2011