Python基础入门:使用openpyxl读写Excel文件
生活随笔
收集整理的這篇文章主要介紹了
Python基础入门:使用openpyxl读写Excel文件
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
Python中常用的操作Excel的三方包有xlrd,xlwt和openpyxl等,xlrd支持讀取.xls和.xlsx格式的Excel文件,只支持讀取,不支持寫入。xlwt只支持寫入.xls格式的文件,不支持讀取。
openpyxl不支持.xls格式,但是支持.xlsx格式的讀取寫入,并且支持寫入公式等。
原始數(shù)據(jù)文件apis.xlsx內(nèi)容:
| 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} |
讀取數(shù)據(jù)
讀取所有數(shù)據(jù)
import openpyxl# 打開excel excel = openpyxl.load_workbook('apis.xlsx') # 有路徑應(yīng)帶上路徑 # 使用指定工作表 sheet = excel.active # 當(dāng)前激活的工作表 # sheet = excel.get_sheet_by_name('Sheet1') # 讀取所有數(shù)據(jù) print(list(sheet.values)) # sheet.values 生成器 print(sheet.max_column) # 最大列數(shù) print(sheet.max_row) # 最大行數(shù)顯示結(jié)果:
[('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) # 讀取標(biāo)題行 for row in sheet.iter_rows(max_row=1):title_row = [cell.value for cell in row] print(title_row) # 讀取標(biāo)題行以外數(shù)據(jù) for row in sheet.iter_rows(min_row=2):row_data = [cell.value for cell in row]print(row_data)打印結(jié)果:
(<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]讀取單元格數(shù)據(jù)
代碼接上例
# 讀取單元格數(shù)據(jù) print(sheet['A1'].value) print(sheet.cell(1,1).value) # 索引從1開始打印結(jié)果:
Copy name name寫入文件
代碼接上例
''' 學(xué)習(xí)中遇到問題沒人解答?小編創(chuàng)建了一個Python學(xué)習(xí)交流QQ群:725638078 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學(xué)習(xí)教程和PDF電子書! ''' # 寫入單元格 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")寫入結(jié)果:
| 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 |
總結(jié)
以上是生活随笔為你收集整理的Python基础入门:使用openpyxl读写Excel文件的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python基础入门:分支及循环
- 下一篇: Python基础中一些高效的数据操作,可