Python Tablib导出数据为Excel、JSON、CSV等格式
Tablib是一个与表格格式有关的Python库,支持以下导出格式:
- Excel (Sets + Books)
- JSON (Sets + Books)
- YAML (Sets + Books)
- HTML (Sets)
- TSV (Sets)
- CSV (Sets)
示例
生成一个新数据集
1headers = ('first_name', 'last_name')
2data = [
3 ('John', 'Adams'),
4 ('George', 'Washington')
5]
6data = tablib.Dataset(*data, headers=headers)
添加新行
1>>> data.append(('Henry', 'Ford'))
添加新列
1>>> data.append_col((90, 67, 83), header='age')
导出为JSON格式
1>>> print data.json
2[
3 {
4 "last_name": "Adams",
5 "age": 90,
6 "first_name": "John"
7 },
8 {
9 "last_name": "Ford",
10 "age": 83,
11 "first_name": "Henry"
12 }
13]
其他导出格式示例:
1>>> data = tablib.Dataset(*[('Kenneth', 'Reitz', 23), ('Bessie', 'Monke', 22)],
2 headers=['First Name', 'Last Name', 'Age'])
3>>> data.json
4[{"Last Name": "Reitz", "First Name": "Kenneth", "Age": 22}, {"Last Name": "Monke", "First Name": "Bessie", "Age": 21}]
5>>> data.yaml
6- {Age: 22, First Name: Kenneth, Last Name: Reitz}
7- {Age: 21, First Name: Bessie, Last Name: Monke}
8>>> data.xlsx
9<censored binary data>
更多功能和例子请参考github主页:https://github.com/kennethreitz/tablib
捐赠本站(Donate)
如您感觉文章有用,可扫码捐赠本站!(If the article useful, you can scan the QR code to donate))
- Author: shisekong
- Link: https://blog.361way.com/python-tablib/4517.html
- License: This work is under a 知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议. Kindly fulfill the requirements of the aforementioned License when adapting or creating a derivative of this work.