Python2-openpyxl operation Excel (the total number of rows acquired, obtaining a row value, obtain the value of a column, set cell values)

 

from openpyxl import *

class excel():
    def __init__(self,file):
        self.file = file
        self.wb = load_workbook(self.file)
        sheets = self.wb.get_sheet_names()
        self.sheet = sheets[0]
        self.ws = self.wb[self.sheet]
        
    # Get the total number of lines and forms the total number of columns 
    DEF getRowsClosNum (Self):
        rows = self.ws.max_row
        columns = self.ws.max_column
        return rows,columns
    
    # Obtain a cell's value 
    DEF getCellValue (Self, Row, column):       
        cellvalue = self.ws.cell(row=row,column=column).value
        return cellvalue
    
    # Get all the values in a column 
    DEF getColValues (Self, column):
        rows = self.ws.max_row
        columndata=[]
        for i in range(1,rows+1):
            cellvalue = self.ws.cell(row=i,column=column).value
            columndata.append(cellvalue)
        return columndata
    
    
    # Get a line all the values 
    DEF getRowValues (Self, Row):
        columns = self.ws.max_column
        rowdata=[]
        for i in range(1,columns+1):
            cellvalue = self.ws.cell(row=row,column=i).value
            rowdata.append(cellvalue)
        return rowdata
    
    # Set the value of a cell 
    DEF setCellValue (Self, Row, Colunm, CellValue):
         the try :
            self.ws.cell(row=row,column=colunm).value=cellvalue
            self.wb.save(self.file)
        except:
            self.ws.cell(row=row,column=colunm).value="writefail"
            self.wb.save(self.file)

 

Guess you like

Origin www.cnblogs.com/dmtz/p/11091090.html