Python Tablib导出数据为Excel、JSON、CSV等格式

Tablib是一个与表格格式有关的Python库,支持以下导出格式:

  • Excel (Sets + Books)
  • JSON (Sets + Books)
  • YAML (Sets + Books)
  • HTML (Sets)
  • TSV (Sets)
  • CSV (Sets)

详细文档:http://python-tablib.org

示例

生成一个新数据集

headers = ('first_name', 'last_name')
data = [
    ('John', 'Adams'),
    ('George', 'Washington')
]
data = tablib.Dataset(*data, headers=headers)

添加新行

>>> data.append(('Henry', 'Ford'))

添加新列

>>> data.append_col((90, 67, 83), header='age')

导出为JSON格式

>>> print data.json
[
  {
    "last_name": "Adams",
    "age": 90,
    "first_name": "John"
  },
  {
    "last_name": "Ford",
    "age": 83,
    "first_name": "Henry"
  }
]

其他导出格式示例:

>>> data = tablib.Dataset(*[('Kenneth', 'Reitz', 23), ('Bessie', 'Monke', 22)],
                          headers=['First Name', 'Last Name', 'Age'])
>>> data.json
[{"Last Name": "Reitz", "First Name": "Kenneth", "Age": 22}, {"Last Name": "Monke", "First Name": "Bessie", "Age": 21}]
>>> data.yaml
- {Age: 22, First Name: Kenneth, Last Name: Reitz}
- {Age: 21, First Name: Bessie, Last Name: Monke}
>>> data.xlsx
<censored binary data>

更多功能和例子请参考github主页:https://github.com/kennethreitz/tablib

发表评论

您的电子邮箱地址不会被公开。