文档
安装
pip install openpyxl
环境
$ python --version
Python 3.7.0
读取文件示例:将Excel文件读取为json数据
有如下一个文件 data.xlsx
![在这里插入图片描述](https://img-blog.csdnimg.cn/6c0c421ed6304d3bbeef677f49cf239a.png =500x)
实现代码
# -*- coding: utf-8 -*-
import json
from openpyxl.reader.excel import load_workbook
def read_excel(filename):
book = load_workbook(filename)
worksheet = book.worksheets[0]
row_num = 0
titles = []
lst = []
for row in worksheet.rows:
row_num += 1
if row_num == 1:
# 表头
for cell in row:
# 移除空格
value = cell.value.replace(' ', '')
titles.append(value)
else:
# 内容
item = {}
for key, cell in zip(titles, row):
item[key] = cell.value
lst.append(item)
return lst
if __name__ == '__main__':
data = read_excel('./data.xlsx')
print(json.dumps(data, ensure_ascii=False, indent=2))
输出读取的json数据
[
{
"姓名": "曹操",
"国家": "魏国"
},
{
"姓名": "刘备",
"国家": "蜀国"
},
{
"姓名": "孙权",
"国家": "吴国"
}
]