python - 将数据转换成 excl 表格, json 等文件 (dajngo - 打开网页后自动下载)

本篇只讲述怎么用。

具体 tablib  更多详细用法可参考博客 : https://blog.csdn.net/liangyuannao/article/details/41476277

# 不得不说  tablib  模块是真的好使。

一。 运行脚本将文件存入本地

import tablib


headers = ('商品名称', '数量', '单价', '合计')
data = [
    ['orange', '1', '5', '5'],
    ['apple', '2', '6', '12']
]
data = tablib.Dataset(*data, headers=headers, title="数据")
myfile = open('mydata.xlsx', 'wb')
myfile.write(data.xlsx)
myfile.close()

二。 打开网页后自动下载。

def download_file(request, *args, **kwargs):
    headers = ('商品名称', '数量', '单价', '合计')
    data = [
        ['orange', '1', '5', '5'],
        ['apple', '2', '6', '12']
    ]
    data = tablib.Dataset(*data, headers=headers, title="数据")

    response = HttpResponse(data.xlsx, content_type='application/vnd.ms-excel')
    response['Content-Disposition'] = 'attachment; filename=水果销售数据统计.xlsx'
    return response

猜你喜欢

转载自www.cnblogs.com/chaoqi/p/11704997.html