[英]write csv from dictionary
祝大家有美好的一天
我想從字典中寫入一個csv文件。 並遵循這里的所有內容https://docs.djangoproject.com/en/dev/howto/outputting-csv/我只是將csv_data更改為字典
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="some_file(%s).csv"'
csv_data = {'data' : [('quick', 'brown', 'fox', 'jump'), ('over', 'the', 'lazy', 'dog'), 'total' : 23, 'subtotal': 4}
t = loader.get_template('main/report/contract_position.txt')
c = Context({
'csv_data' : csv_data,
})
response.write(t.render(c))
return response
在我的.txt文件中
"header1", "header2", "header3", "header4", "total", "subtotal"
{% for item in csv_data %}
???? #what should be here. Cuz I can't do something item.0|addslashes. It only takes out the first character of the string
{% endfor %}
我想在其中產生類似的東西。
header1 header2 header3 header4
quick brown fox jump
over the lazy dog
total subtotal
23 4
任何幫助將非常感激。 謝謝
使用csv
:
import csv
def your_view(request, ...):
csv_data = {
'data': [
('quick', 'brown', 'fox', 'jump'),
('over', 'the', 'lazy', 'dog')
],
'total': 23,
'subtotal': 4
}
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="some_file.csv"'
writer = csv.writer(response, delimiter='\t')
writer.writerow(['header1', 'header2', 'header3', 'header4'])
writer.writerows(csv_data['data'])
writer.writerow(['tota', 'subtotal'])
writer.writerow([csv_data['total'], csv_data['subtotal']])
return response
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.