Python3利用openpyxl讀寫Excel文件的方法實例

前言

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

更多操作可參考官方文檔: https://openpyxl.readthedocs.io/en/stable/

總結

到此這篇關於Python3利用openpyxl讀寫Excel文件的文章就介紹到這瞭,更多相關Python3用openpyxl讀寫Excel文件內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: