openpyxl 是 python 中操作 excel 表格比較常用的一個(gè)庫(kù),可以讀取和寫(xiě)入excel文件,支持【.xlsx / .xlsm / .xltx / .xltm】格式的文件,處理excel數(shù)據(jù)、公式、樣式,且可以在表格內(nèi)插入圖表
但是在實(shí)際項(xiàng)目的使用過(guò)程中,如果經(jīng)常要用到 openpyxl 進(jìn)行操作,進(jìn)行相應(yīng)的封裝,會(huì)事半功倍
from openpyxl import load_workbook
from openpyxl.worksheet.worksheet import Worksheet
class ExcelHandler():
'''
操作Excel
'''
def __init__(self, file):
'''初始化函數(shù)'''
self.file = file
def open_sheet(self, sheet_name) -> Worksheet:
'''打開(kāi)表單'''
wb = load_workbook(self.file)
sheet = wb[sheet_name]
return sheet
def read_header(self, sheet_name):
'''獲取表單的表頭'''
sheet = self.open_sheet(sheet_name)
headers = []
for i in sheet[1]:
headers.append(i.value)
return headers
def read_rows(self,sheet_name):
'''
讀取除表頭外所有數(shù)據(jù)(除第一行外的所有數(shù)據(jù))
返回的內(nèi)容是一個(gè)二維列表,若想獲取每一行的數(shù)據(jù),可使用for循環(huán)或*解包
'''
sheet = self.open_sheet(sheet_name)
rows = list(sheet.rows)[1:]
data = []
for row in rows:
row_data = []
for cell in row:
row_data.append(cell.value)
data.append(row_data)
return data
def read_key_value(self,sheet_name):
'''
獲取所有數(shù)據(jù),且將表頭中的內(nèi)容與數(shù)據(jù)結(jié)合展示(以字典的形式)
如:[
{'序號(hào)':1,'會(huì)員卡號(hào)': '680021685898','機(jī)場(chǎng)名稱(chēng)':'上海機(jī)場(chǎng)'},
{'序號(hào)':2,'會(huì)員卡號(hào)': '680021685899','機(jī)場(chǎng)名稱(chēng)':'廣州機(jī)場(chǎng)'}
]
'''
sheet = self.open_sheet(sheet_name)
rows = list(sheet.rows)
# 獲取標(biāo)題
data = []
for row in rows[1:]:
rwo_data = []
for cell in row:
rwo_data.append(cell.value)
# 列表轉(zhuǎn)換成字典,與表頭里的內(nèi)容使用zip函數(shù)進(jìn)行打包
data_dict = dict(zip(self.read_header(sheet_name),rwo_data))
data.append(data_dict)
return data
@staticmethod
def write_change(file,sheet_name,row,column,data):
'''寫(xiě)入Excel數(shù)據(jù)'''
wb = load_workbook(file)
sheet = wb[sheet_name]
# 修改單元格
sheet.cell(row,column).value = data
# 保存
wb.save(file)
# 關(guān)閉
wb.close()
寫(xiě)入Excel數(shù)據(jù)這一步,使用了靜態(tài)方法,原因是讀取文件可以無(wú)需保存,而修改文件后,如果沒(méi)有進(jìn)行保存,而其他地方有調(diào)用了該方法,則會(huì)引起一些報(bào)錯(cuò),所以,每對(duì)excel進(jìn)行一次修改,都進(jìn)行一次保存
import os
from ExcelDemo.config.excel_handler import ExcelHandler
from ExcelDemo.config import dir_config
excelfile = os.path.join(dir_config.excel_dir,'航班信息.xlsx')
if __name__ == '__main__':
excel = ExcelHandler(excelfile)
header = excel.read_header('Sheet1')
data = excel.read_rows('Sheet1')
data2 = excel.read_key_value('Sheet1')
print(header)
'''
['序號(hào)', '會(huì)員卡號(hào)', '機(jī)場(chǎng)', '航班日期', '航班號(hào)']
'''
print('**********************************')
print(data)
'''
[
[1, '680021685898', '西安南航', 20200503, 'CZ6754'],
[2, '189000177074', '(新疆)莎車(chē)機(jī)場(chǎng)', 20200603, 'CZ6880'],
[3, '480005387697', '新疆南航', 20200612, 'CZ5390'],
[4, '380025990156', '西安南航', 20200619, 'CZ6622']
]
'''
print('**********************************')
print(data2)
'''
[
{'序號(hào)': 1, '會(huì)員卡號(hào)': '680021685898', '機(jī)場(chǎng)': '西安南航', '航班日期':20200503, '航班號(hào)': 'CZ6754'},
{'序號(hào)': 2, '會(huì)員卡號(hào)': '189000177074', '機(jī)場(chǎng)': '(新疆)莎車(chē)機(jī)場(chǎng)', '航班日期': 20200603, '航班號(hào)': 'CZ6880'},
{'序號(hào)': 3, '會(huì)員卡號(hào)': '480005387697', '機(jī)場(chǎng)': '(新疆)庫(kù)車(chē)', '航班日期': 20200612, '航班號(hào)': 'CZ5390'},
{'序號(hào)': 4, '會(huì)員卡號(hào)': '380025990156', '機(jī)場(chǎng)': '西安南航', '航班日期': 20200619, '航班號(hào)': 'CZ6622'}
]
'''
excel.write_change(excelfile,'Sheet1',6,5,'新增內(nèi)容')
excel.write_change(excelfile,'Sheet1',2,3,'修改內(nèi)容')
到此這篇關(guān)于使用Python封裝excel操作的文章就介紹到這了,更多相關(guān)Python封裝excel操作內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!