Python-openpyxl manipulate Excel files

1. pip install openpyxl library

pip3 install openpyxl

2. When you start using openpyxl, you don't need to create a file in the file system, just import the workbook class:

from openpyxl import Workbook

If you only read file data, you can choose to load only:

from openpyxl import load_workbook

Or directly import the entire openpyxl package:

import openpyxl

3. Load the Excel file into memory and get its workbook object

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. Get the sheet object according to the sheet name

    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. Get the sheet name according to the index number

    def getSheetByIndex(self,sheetIndex):
        # 根据sheet的索引号获取该sheet名称
        try:
            #只获取到sheet名称,不能获取该sheet对象
            sheetname = self.workBook.sheetnames[sheetIndex]
            return sheetname
        except Exception as e:
            raise e

6. Get all the sheet names of the workbook object and return a list

    def getAllSheetNames(self):
        # 获取workbook对象所有的sheet名称,返回列表
        try:
            return self.workBook.sheetnames
        except Exception as e:
            raise e

7. Get the maximum row number of the data area in the sheet

    def getRowsNumber(self,sheet):
        # 获取sheet中有数据区域的结束行号
        return sheet.max_row

8. Get the smallest row number of the data area in the sheet

    def getStartRowNumber(self,sheet):
        # 获取sheet中有数据区域的开始的行号
        return sheet.min_row

9. Get the maximum column number of the data area in the sheet

    def getColumnsNumber(self,sheet):
        # 获取sheet中有数据区域的结束列号
        return sheet.max_column

10. Get the smallest column number of the data area in the sheet

    def getStartColumnNumber(self,sheet):
        # 获取sheet中有数据区域的开始的列号
        return sheet.min_column

11. Get the value of a row in the sheet and return the list object

    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

Passing parameters: sheet object, line number 1:

    rowDate = e.getRowValue(sheet,1)
    print(rowDate)

Return the data of the first row of the sheet:

	['编号', '需求编号', '需求名称', '开发负责人', '是否提测', '小机房环境测试情况', '生产环境测试情况', '备注']

12. Get the value of a column in the sheet and return the list object

    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

Passing parameters: sheet object, column number 1:

    colDate = e.getColValue(sheet,1)
    print(colDate)

Return a list of column values:

	['编号', 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]

13. Get the value in the cell according to the row and column position index or coding coordinates of the cell, and the subscript starts from 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

Get the value of the cell by the row and column number:

    # 通过行列号获取value
    value = e.getCellOfValue(sheet,rowNumber=1,colNumber=2)
    print(value)
	需求编号
	Process finished with exit code 0

14. Write data to the cell according to the coding coordinates or numeric index coordinates (row and column number) of the cell in 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

Write
Write data to the cell by number index coordinates, the subscript starts from 1:

    sheet2 = e.getSheetByName(sheetName="empty")
    content = "hello world!"
    e.writeCell(sheet2,content,rowNumber=1,colNumber=2)
	写入成功!
	Process finished with exit code 0

Insert picture description here
Pay special attention to the fact that you must close the file first when writing data to the file, otherwise an error will be reported:

PermissionError: [Errno 13] Permission denied: 'C:\\Users\\Administrator\\Desktop\\客户需求测试情况.xlsx'

15. In the same way, you can also write the current time into the cell, and the number index subscript starts from 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

Write to the cell by coding coordinates:

    e.writeCellCurrentTime(sheet2,coordinate="C1")

Write to the cell by number index subscript:

    e.writeCellCurrentTime(sheet2,rowNumber=1,colNumber=4)

Insert picture description here
16. Add a row of data to the sheet. The data can be lists, tuples, range objects, dictionaries, generators, etc.:

    def appendDate(self,sheet,content):
        # sheet页追加一行数据,参数可以是列表、元组、range对象、字典、生成器
        try:
            sheet.append(content)
            self.workBook.save(self.excelFile)
            print("保存成功!")
        except Exception as e:
            raise e

Write dictionary data:

    content = {
    
    "A":1,"B":2,"D":4,"F":5,"G":6}
    e.appendDate(sheet2,content)

Insert picture description here
17. Insert data in the specified row:

    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

Passing parameters: sheet object, content to be written in content, row number index:

    content = ["q","w","e","r","t","y"]
    e.insertDate(sheet2,content,rowNumber=2)

Insert picture description here
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_52385863/article/details/112995710