1、pip安装openpyxl库
pip3 install openpyxl
2、开始使用openpyxl时,无需在文件系统中创建文件,只要导入workbook类就可以了:
from openpyxl import Workbook
若只读取文件数据可以选择只加载方式:
from openpyxl import load_workbook
或是直接导入整个openpyxl包:
import openpyxl
3、将Excel文件加载到内存中,并获取其workbook对象
class ParseExcel():
def __init__(self):
self.workBook = None
self.excelFile = None
self.font = Font(color=None)
self.RGBdict = {"red":"FFFF3030","GREEN":"FF008B00"}
def loadWorkBook(self,excelPathAndName):
# 将Excel文件加载到内存,并获取其workbook对象
try:
self.workBook = openpyxl.load_workbook(excelPathAndName)
except Exception as e:
raise e
self.excelFile = excelPathAndName
return self.workBook
4、根据sheet名获取该sheet对象
def getSheetByName(self,sheetName):
# 根据sheet名获取该sheet对象
try:
# sheet1 = self.workBook.get_sheet_by_name(sheetName) 该调用方法已经弃用
self.sheet = self.workBook[sheetName]
return self.sheet
except Exception as e:
raise e
5、根据索引号获取该sheet名称
def getSheetByIndex(self,sheetIndex):
# 根据sheet的索引号获取该sheet名称
try:
#只获取到sheet名称,不能获取该sheet对象
sheetname = self.workBook.sheetnames[sheetIndex]
return sheetname
except Exception as e:
raise e
6、获取workbook对象所有的sheet名称,返回一个列表
def getAllSheetNames(self):
# 获取workbook对象所有的sheet名称,返回列表
try:
return self.workBook.sheetnames
except Exception as e:
raise e
7、获取sheet中数据区域的最大行号
def getRowsNumber(self,sheet):
# 获取sheet中有数据区域的结束行号
return sheet.max_row
8、获取sheet中数据区域最小行号
def getStartRowNumber(self,sheet):
# 获取sheet中有数据区域的开始的行号
return sheet.min_row
9、获取sheet中数据区域的最大列号
def getColumnsNumber(self,sheet):
# 获取sheet中有数据区域的结束列号
return sheet.max_column
10、获取sheet中数据区域的最小列号
def getStartColumnNumber(self,sheet):
# 获取sheet中有数据区域的开始的列号
return sheet.min_column
11、获取sheet中某一行的值,返回list对象
def getRowValue(self,sheet,rowNumber):
# 下表从1开始,sheet.rows[1]表示一行
try:
# return sheet.rows[rowNumber-1] 因为sheet.rows是生成器类型,不能使用索引
# 转换成list之后在使用索引,list(sheet.rows)[2]这样就能获取到第二行的tuple对象
# 获取sheet中某一行,返回的是这一行所有数据内容对象组成tuple
tuple = list(sheet.rows)[rowNumber-1]
# 用list接收该行的值,返回列表对象
rowDate = []
for i in tuple:
rowDate.append(i.value)
return rowDate
except Exception as e:
raise e
传参:sheet对象,行号1:
rowDate = e.getRowValue(sheet,1)
print(rowDate)
返回该sheet第一行的数据:
['编号', '需求编号', '需求名称', '开发负责人', '是否提测', '小机房环境测试情况', '生产环境测试情况', '备注']
12、获取sheet中某一列的值,返回list对象
def getColValue(self, sheet, colNumber):
# 获取sheet中某一列,返回的是这一列所有数据内容组成的tuple
# 元组中的元素为cell对象,元素.value为该元素的值
# 下标从1开始,sheet.columns[1]表示第一列
try:
tuple = list(sheet.columns)[colNumber-1]
# 用list接受该列值,返回列表对象
colDate = []
for i in tuple:
colDate.append(i.value)
return colDate
except Exception as e:
raise e
传参:sheet对象,列号1:
colDate = e.getColValue(sheet,1)
print(colDate)
返回列值列表:
['编号', 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
13、根据单元格所在的行列位置索引或编码坐标获取该单元格中的值,下标从1开始
def getCellOfValue(self,sheet,coordinate=None,rowNumber=None,colNumber=None):
# 根据单元格所在的位置索引获取该单元格中的值,下标从1开始
# sheet.cell(row=1,column=1).value,表示excel中的第一行第一列的值
if coordinate is not None:
try:
return sheet[coordinate].value
except Exception as e:
raise e
elif coordinate is None and rowNumber is not None and colNumber is not None:
try:
return sheet.cell(row=rowNumber,column=colNumber).value
except Exception as e:
raise e
else:
raise Exception("Insufficient Coordinate of cell!")
通过单元格编码坐标获取值:
# 通过单元格坐标获取值
value = e.getCellOfValue(sheet,coordinate="A1")
print(value)
编号
Process finished with exit code 0
通过行列号获取单元格的值:
# 通过行列号获取value
value = e.getCellOfValue(sheet,rowNumber=1,colNumber=2)
print(value)
需求编号
Process finished with exit code 0
14、根据单元格在Excel中的编码坐标或者数字索引坐标(行列号)向单元格中写入数据:
def writeCell(self,sheet,content,coordinate=None,rowNumber=None,colNumber=None,style=None):
# 根据单元格在Excel中的编码坐标或者数字索引坐标向单元格中写入数据,下标从1开始
# 参数style表示字体的颜色的名字,如red,green
if coordinate is not None:
try:
sheet[coordinate].value = content
if style is not None:
sheet.cell(coordinate=coordinate).font = Font(color=self.RGBdict[style])
self.workBook.save(self.excelFile)
except Exception as e:
raise e
elif coordinate is None and rowNumber is not None and colNumber is not None:
try:
sheet.cell(row=rowNumber,column=colNumber).value = content
if style is not None:
sheet.cell(row=rowNumber,column=colNumber).font = Font(color=self.RGBdict[style])
self.workBook.save(self.excelFile)
print("保存成功!")
except Exception as e:
raise e
else:
raise Exception("Insufficient Coordinate of cell!")
通过编码坐标向单元格中写入数据:
# 先获取到要写入数据的sheet2对象
sheet2 = e.getSheetByName(sheetName="empty")
content = "这是写入的内容"
e.writeCell(sheet2,content,coordinate="A1")
写入成功!
Process finished with exit code 0
通过数字索引坐标向单元格写入数据,下标从1开始:
sheet2 = e.getSheetByName(sheetName="empty")
content = "hello world!"
e.writeCell(sheet2,content,rowNumber=1,colNumber=2)
写入成功!
Process finished with exit code 0
特别注意,在向文件写入数据时候务必要先关闭文件,否则会报错:
PermissionError: [Errno 13] Permission denied: 'C:\\Users\\Administrator\\Desktop\\客户需求测试情况.xlsx'
15、同理,也可以向单元格中写入当前时间,数字索引下标从1开始:
def writeCellCurrentTime(self,sheet,coordinate=None,rowNumber=None,colNumber=None):
# 写入当前时间,下标从1开始
localTime = time.localtime(time.time())
currentTime = time.strftime("%Y-%m-%d %H-%M-%S",localTime)
if coordinate is not None:
try:
sheet[coordinate].value = currentTime
self.workBook.save(self.excelFile)
print("保存成功!")
except Exception as e:
raise e
elif coordinate is None and rowNumber is not None and colNumber is not None:
try:
sheet.cell(row=rowNumber,column=colNumber).value = currentTime
self.workBook.save(self.excelFile)
print("保存成功!")
except Exception as e:
raise e
通过编码坐标向单元格写入:
e.writeCellCurrentTime(sheet2,coordinate="C1")
通过数字索引下标向单元格写入:
e.writeCellCurrentTime(sheet2,rowNumber=1,colNumber=4)
16、在sheet中追加一行数据,数据可以是列表、元组、range对象、字典、生成器等:
def appendDate(self,sheet,content):
# sheet页追加一行数据,参数可以是列表、元组、range对象、字典、生成器
try:
sheet.append(content)
self.workBook.save(self.excelFile)
print("保存成功!")
except Exception as e:
raise e
写入字典数据:
content = {"A":1,"B":2,"D":4,"F":5,"G":6}
e.appendDate(sheet2,content)
17、在指定行插入数据:
def insertDate(self,sheet,content,rowNumber=-1):
'''sheet页中在对应行插入数据'''
try:
# 在对应行号插入空行,插入的空行索引号变为rowNumber值
sheet.insert_rows(rowNumber)
# 取出content中的元素写入到对应的单元格中
for index,content_value in enumerate(content):
sheet.cell(row=rowNumber, column=index+1).value = content_value
self.workBook.save(self.excelFile)
print("数据写入成功!")
except Exception as e:
raise e
传参:sheet对象,content要写入的内容,行号索引:
content = ["q","w","e","r","t","y"]
e.insertDate(sheet2,content,rowNumber=2)