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

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

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

示例

生成一个新数据集

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