前言

python中常用的操作excel的三方包有xlrd,xlwt和openpyxl等,xlrd支持读取.xls和.xlsx格式的excel文件,只支持读取,不支持写入。xlwt只支持写入.xls格式的文件,不支持读取。

openpyxl不支持.xls格式,但是支持.xlsx格式的读取写入,并且支持写入公式等。

原始数据文件apis.xlsx内容:

name method url data json result
get接口 get https://httpbin.org/get?a=1&b=2
post表单接口 post https://httpbin.org/post {name: kevin,age:1}
post-json接口 post https://httpbin.org/post {name: kevin,age: 21}

读取数据

读取所有数据

import openpyxl

# 打开excel
excel = openpyxl.load_workbook('apis.xlsx') # 有路径应带上路径
# 使用指定工作表
sheet = excel.active # 当前激活的工作表
# sheet = excel.get_sheet_by_name('sheet1')
# 读取所有数据
print(list(sheet.values)) # sheet.values 生成器
print(sheet.max_column) # 最大列数
print(sheet.max_row) # 最大行数

显示结果:

[(‘name’, ‘method’, ‘url’, ‘headers’, ‘data’, ‘json’, ‘result’), (‘get接口’, ‘get’, ‘https://httpbin.org/get?a=1&b=2’, none, none, none, none), (‘post表单接口’, ‘post’, ‘https://httpbin.org/post’, ‘cookie: token=123’, ‘{name: kevin,age: 21}’, none, none), (‘post-json接口’, ‘post’, ‘https://httpbin.org/post’, none, none, ‘{name: kevin,age: 21}’, none)]
7
4

按行读取

代码接上例

 ...
# 按行读取
for row in sheet.iter_rows(min_row=1, min_col=1, max_col=3, max_row=3): 
 print(row)
# 读取标题行
for row in sheet.iter_rows(max_row=1):
 title_row = [cell.value for cell in row]
print(title_row)
# 读取标题行以外数据
for row in sheet.iter_rows(min_row=2):
 row_data = [cell.value for cell in row]
 print(row_data)

打印结果:

(<cell ‘sheet1’.a1>, <cell ‘sheet1’.b1>, <cell ‘sheet1’.c1>)
(<cell ‘sheet1’.a2>, <cell ‘sheet1’.b2>, <cell ‘sheet1’.c2>)
(<cell ‘sheet1’.a3>, <cell ‘sheet1’.b3>, <cell ‘sheet1’.c3>)
[‘name’, ‘method’, ‘url’, ‘headers’, ‘data’, ‘json’, ‘result’]
[‘get接口’, ‘get’, ‘https://httpbin.org/get?a=1&b=2’, none, none, none, none]
[‘post表单接口’, ‘post’, ‘https://httpbin.org/post’, ‘cookie: token=123’, ‘{name: kevin,age: 21}’, none, none]
[‘post-json接口’, ‘post’, ‘https://httpbin.org/post’, none, none, ‘{name: kevin,age: 21}’, none]

读取单元格数据

代码接上例

...
# 读取单元格数据
print(sheet['a1'].value)
print(sheet.cell(1,1).value) # 索引从1开始

打印结果:

name
name

写入文件

代码接上例

# 写入单元格
sheet['f2'] = 'pass'
result_col = title_row.index('result')+1 # 'result'所在的列号
sheet.cell(3, result_col).value = 'pass'
# 整行写入
new_row = ['post-xml接口', 'post', 'https://httpbin.org/post']
sheet.append(new_row)
# 保存文件,也可覆盖原文件
excel.save("apis2.xlsx")

写入结果:

name method url data json result
get接口 get https://httpbin.org/get?a=1&b=2 pass
post表单接口 post https://httpbin.org/post {name: kevin,age:1} pass
post-json接口 post https://httpbin.org/post {name: kevin,age: 21}
post-xml接口 post https://httpbin.org/post

更多操作可参考官方文档:

总结

到此这篇关于python3利用openpyxl读写excel文件的文章就介绍到这了,更多相关python3用openpyxl读写excel文件内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!