openpyxl 介绍
openpyxl 是一个 Python 库,用于读取/写入 Excel 2010 xlsx/xlsm/xltx/xltm 文件。它是由于缺乏现有的库来从 Python 本地读取/写入 Office Open XML 格式而诞生的
安装openpyxl
pip install openpyxl
定义操作Excel的class
import openpyxl
class InAndOutExcel(object):
"""
读取Excel数据
:param filePath: 文件路径
:returns: Excel数据的字典
"""
def inXlsx(self, filePath):
workbook = openpyxl.load_workbook(filePath)
sheets = workbook.sheetnames
tab = workbook.get_sheet_by_name(sheets[0])
rows = tab.max_row
cols = tab.max_column
print(f"行数: {rows}; 列数: {cols}")
data = []
for i in range(1, rows + 1, 1):
temp = []
for j in range(1, cols + 1, 1):
temp.append(tab.cell(i, j).value)
data.append(temp)
return data
"""
读取Excel数据
:param filePath: 文件路径
:param data: 需要导出的数据
"""
def outXlsx(self, filePath, data):
target_list = data
wb = openpyxl.Workbook()
ws = wb.active
rows = len(target_list)
lines = len(target_list[0])
for i in range(rows):
for j in range(lines):
ws.cell(row=i + 1, column=j + 1).value = target_list[i][j]
wb.save(filename=filePath)
使用
import uuid
if __name__ == '__main__':
inAndOutExcel = InAndOutExcel()
data = inAndOutExcel.inXlsx(r"D:\aaaaaa\test.xlsx")
num = 1
for i in range(len(data)):
print(num, end="\t")
print(data[i])
num += 1
data = [
('a', 'b', 'c', 'd', 'e', 'f'),
('aa', 'bb', 'cc', 'dd', 'ee', 'ff'),
('aaa', 'bbb', 'cc', 'ddd', 'eee', 'fff')
]
id = str(uuid.uuid1()).replace("-", "")
fileName = rf"D:\aaaaaa\{id}.xlsx"
inAndOutExcel.outXlsx(data=data, fileName=fileName)
|