前言
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"htmlcode">
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"htmlcode">
... # 按行读取 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"htmlcode">... # 读取单元格数据 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"external nofollow" target="_blank" href="https://openpyxl.readthedocs.io/en/stable/">https://openpyxl.readthedocs.io/en/stable/总结
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
更新日志
- 华少翌.2005-华少翌【中唱艺能】【WAV+CUE】
- 群星《十二女声Ⅱ》[WAV/CUE/分轨][527MB]
- 大自然音乐系列《漫步在山裡》[WAV/CUE/分轨][502.8MB]
- 大自然音乐系列《星光夜语》[WAV/CUE/分轨][453.3MB]
- 史依弘《史依弘交响乐京剧演唱专辑HQ》头版限量编号[WAV+CUE]
- 曼丽2020《女人三十风继续吹》HQCD[WAV+CUE]
- 曼丽2021《女人三十2雾之恋》HQCD[WAV+CUE]
- 隔壁老樊.2019-我曾【好听音乐】【FLAC分轨】
- 高林生.1993-牵挂你的人是我【白天鹅】【WAV+CUE】
- 洪卓立.2012-找个懂我的女孩(国专)【英皇娱乐】【WAV+CUE】
- 曼丽2022《女人三十3晚秋》HQCD[WAV+CUE]
- 曼丽2018《女人三十4冬天》HQCD[WAV+CUE]
- 柏菲-《好歌30年壹》限量开盘母带ORMCD[低速原抓WAV+CUE]
- 大自然音乐系列《水舞》[WAV/CUE/分轨][424.3MB]
- 大自然音乐系列《星光夜语》[WAV/CUE/分轨][453.3MB]