Python中常用的操作Excel的三方包有xlrd,xlwt和openpyxl等,xlrd支持读取.xls和.xlsx格式的Excel文件,只支持读取,不支持写入。xlwt只支持写入.xls格式的文件,不支持读取。
openpyxl不支持.xls格式,但是支持.xlsx格式的读取写入,并且支持写入公式等。
原始数据文件apis.xlsx内容:
读取数据
读取所有数据
import openpyxl# 打开excelexcel = 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', '/get?a=1&b=2', None, None, None, None), ('post表单接口', 'post', '/post', 'cookie: token=123', '{name: Kevin,age: 21}', None, None), ('post-json接口', 'post', '/post', None, None, '{name: Kevin,age: 21}', None)]74
按行读取
代码接上例
# 按行读取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', '/get?a=1&b=2', None, None, None, None]['post表单接口', 'post', '/post', 'cookie: token=123', '{name: Kevin,age: 21}', None, None]['post-json接口', 'post', '/post', None, None, '{name: Kevin,age: 21}', None]
读取单元格数据
代码接上例
# 读取单元格数据print(sheet['A1'].value)print(sheet.cell(1,1).value) # 索引从1开始
打印结果:
Copynamename
写入文件
代码接上例
'''学习中遇到问题没人解答?小编创建了一个Python学习交流QQ群:725638078寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!'''# 写入单元格sheet['F2'] = 'PASS'result_col = title_row.index('result')+1 # 'result'所在的列号sheet.cell(3, result_col).value = 'PASS'# 整行写入new_row = ['post-xml接口', 'post', '/post']sheet.append(new_row)# 保存文件,也可覆盖原文件excel.save("apis2.xlsx")
写入结果: