有如下格式的数据需要输出到csv,数据示例:
invoices = [{‘id’: 1451L, ‘note’: ‘ABC’, ‘payout’: 1.1, ‘profit’: 0.25},
{‘id’: 1452L, ‘note’: ‘QWE’, ‘payout’: 1512.66, ‘profit’: 179.39}]
fieldnames = [‘id’, ‘note’, ‘payout’, ‘profit’]
1.字符串手动csv
csv文件使用“,”作为分割符,也就是输出的.csv文件中,“,”会被作为列间隔来解析
1.首先拼出表头
# 输出BOM头,使得文件被打开的时候以UTF-8解析
header = '\xEF\xBB\xBF' + '\n'
header += ','.join(fieldnames) + '\n'
2.拼出数据部分
content = ''
for invoice in invoices:
values = ','.join([str(invoice[field]) for field in fieldnames]) + '\n'
content += values
csv_data = header + content
3. 设置cherrypy response header
cherrypy.response.headers.update({
'Content-Type': 'application/octet-stream',
'Content-Disposition': 'attachment; filename=%s' % csv_name})
把csv_data作为response的body返回, 其中filename参数为文件名,也就是浏览器下载该文件后保存的文件名称
2.使用csv module生成csv
1.csv.writer
csv.writer(),接受一个以‘b’模式打开的文件对象作为参数, 可以指定csv文件的分隔符
csv.writerow(),接受iterata