Python-openpyxl表格讀取寫入的案例詳解
1.為何選擇openpyxl模塊
xlxd、xlwt、–只能讀取,openpyxl、可以讀取寫入
2.安裝
pip install -i https://pypi.douban.com/simple openpyxl==2.6.2
3.處理對(duì)象
openpyxl只能處理xlsx格式的excel文件,只能使用辦公軟件來創(chuàng)建xlsx格式的excel文件,不能使用pycharm來創(chuàng)建
excel對(duì)象 -> sheet表單對(duì)象 -> cell單元格對(duì)象 -> 行和列、值屬性
如果excel文件不存在,那么會(huì)FileNotFoundError
res = load_workbook(“testcase11.xlsx”)
4.代碼案例
from openpyxl import load_workbook # load_workbook,往往對(duì)已存在的excel進(jìn)行讀寫操作 class Handle_excel: def __init__(self,filename,sheetname = None): self.filename = filename self.sheetname = sheetname def read_data(self): """ 讀取表格數(shù)據(jù) :return: """ wb = load_workbook(self.filename) if self.sheetname is None: ws = wb.active # active默認(rèn)讀取第一個(gè)表單 else: ws = wb[self.sheetname] # 讀取指定表單 testcase_list = [] # 所有數(shù)據(jù)信息 header_list = [] # 表頭信息 for row in range(1,ws.max_row+1): one_row_dict = {} # 每一行數(shù)據(jù)信息 for column in range(1,ws.max_column+1): one_cell_value = ws.cell(row,column).value # cell方法,獲取單元格,返回Cell對(duì)象 if row == 1: header_list.append(one_cell_value) else: key = header_list[column-1] one_row_dict[key] = one_cell_value if row != 1: testcase_list.append(one_row_dict) return testcase_list def write_data(self, row, column, data): """ 寫操作 :param row: 指定在某一行寫 :param column: 指定在某一列寫 :param data: 待寫入的數(shù)據(jù) :return: """ # 將數(shù)據(jù)寫入到excel中,不能與讀取操作公用一個(gè)Workbook對(duì)象 # 如果使用同一個(gè)Workbook對(duì)象,只能將最后一次寫入成功,會(huì)出現(xiàn)意想不到的結(jié)果 wb = load_workbook(self.filename) if self.sheetname is None: ws = wb.active else: ws = wb[self.sheetname] # 第一種寫入方式: # one_cell = ws.cell(row, column) # one_cell.value = data # 第二種寫入方式: ws.cell(row, column, value=data) # c.PermissionError: [Errno 13] Permission denied: 'testcase.xlsx' # 對(duì)exel文件修改之后,要保存,一定要將excel文件關(guān)閉 wb.save(self.filename) if __name__ == "__main__": excel_name =“testcase.xlsx" sheet_name = "login" do_excel = Handle_excel(excel_name,sheet_name) print(do_excel.read_data()) #do_excel.write_data(3,4,5)
到此這篇關(guān)于Python-openpyxl表格讀取寫入的案例詳解的文章就介紹到這了,更多相關(guān)Python表格讀取寫入內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python paramiko 模塊淺談與SSH主要功能模擬解析
這篇文章主要介紹了Python paramiko 模塊詳解與SSH主要功能模擬,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-02-02Python使用pymssql連接SQL?SEVER數(shù)據(jù)庫全流程
SQL Server是微軟推出的重量級(jí)的數(shù)據(jù)庫,目前有多個(gè)版本,如2000、2008、2012等,下面這篇文章主要給大家介紹了關(guān)于Python使用pymssql連接SQL?SEVER數(shù)據(jù)庫的相關(guān)資料,需要的朋友可以參考下2023-12-12python OpenCV的imread不能讀取中文路徑問題及解決
這篇文章主要介紹了python OpenCV的imread不能讀取中文路徑問題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-07-07解決TensorFlow調(diào)用Keras庫函數(shù)存在的問題
這篇文章主要介紹了解決TensorFlow調(diào)用Keras庫函數(shù)存在的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-07-07