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

Tablib是一个与表格格式有关的Python库,支持以下导出格式:
  • Excel (Sets + Books)
  • JSON (Sets + Books)
  • YAML (Sets + Books)
  • HTML (Sets)
  • TSV (Sets)
  • CSV (Sets)
详细文档:<a href="http://python-tablib.org/" class="external" target="_blank" rel="noopener">http://python-tablib.org</a>

示例

生成一个新数据集



<br />
headers = ('first_name', 'last_name')
data = [
    ('John', 'Adams'),
    ('George', 'Washington')
]
data = tablib.Dataset(*data, headers=headers)
添加新行



<br />
>>> data.append(('Henry', 'Ford'))
添加新列



<br />
>>> data.append_col((90, 67, 83), header='age')
导出为JSON格式



<br />
>>> print data.json
[
  {
    "last_name": "Adams",
    "age": 90,
    "first_name": "John"
  },
  {
    "last_name": "Ford",
    "age": 83,
    "first_name": "Henry"
  }
]
其他导出格式示例:



<br />
>>> 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
更多功能和例子请参考github主页:<a href="https://github.com/kennethreitz/tablib" class="external" target="_blank" rel="noopener">https://github.com/kennethreitz/tablib</a>

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注