Reg : Array in Python openpyxl

Viewed 106

I'm trying to read and write some data in Excel using Python with Openpyxl module. Here is the code on which I'm working. I could not able to do with Arrays. It's little difficult to declare many variables. Can Anyone help me in this regard please...

#---------------------------------Code-----------------------------------------------------

    import os    
    import sys    
    from openpyxl import load_workbook    
    List = ["BG1", "BG2"]    
    BG1Cnt: int = 0    
    BG1Run: int = 0    
    BG1Stop: int = 0  
    #Instead of this any better way by handling with array like in VB, using BGCnt(2) etc.
    BG2Cnt: int = 0     
    BG2Run: int = 0    
    BG2Stop: int = 0
    #Instead of this any better way by handling with array like in VB, using BGCnt(2) etc.    
    file = 'C:\\MyDocs\\BG Machine Check.xlsx'    
    book = load_workbook(file)    
    ws1 = book['Sheet1']    
    ws2 = book['Sheet2']    
    iRow = ws1.max_row    
    iCol = ws1.max_column
    
    for i in range(1,iRow):
  
        StrData = (ws1.cell(i, 1).value) 

 #There are so many Cells contains this type of string, which contain the data.
 
 #StrData Example for "Running":"BG1";"Q111SUI6A";"ThinkStation P720";"Workstation";"Running "

 #StrData example for for "Stopped": "BG2";"Q111SUI6A";"ThinkStation P720";"Workstation";"Stopped "

        if ('BG1') in str(StrData ):    
            BG1Cnt = BG1Cnt + 1    
            if 'BG1' in str(StrData ) and 'Running' in (StrData ):    
                BG1Run = BG1Run + 1
    
            if 'BG1' in str(StrData ) and 'Stopped' in (StrData ):    
                BG1Stop = BG1Stop + 1
    
    ws2.cell(3,7).value = BG1Cnt    
    ws2.cell(4,7).value = BG1Run    
    ws2.cell(6,7).value = BG1Stop
    
    book.save(filename=file)

Thanking you in advance.

Regards

1 Answers

I believe that you're looking for a Python Dictionary. This is how you could use a dictionary to count the values.

MachineStates = {
    'BG1Cnt': 0,    
    'BG1Run': 0,   
    'BG1Stop': 0,
    'BG2Cnt': 0,    
    'BG2Run': 0,    
    'BG2Stop': 0 
}

# existing value
x = MachineStates ['BG1Cnt']

StrData  = '"Running":"BG1";"Q111SUI6A";"ThinkStation P720";"Workstation";"Running "'
StrData2 = '"Stopped": "BG2";"Q111SUI6A";"ThinkStation P720";"Workstation";"Stopped "'

if 'BG1' in str(StrData ) and 'Running' in (StrData ):    
    current = MachineStates['BG1Run']
    temp = current + 1
    MachineStates['BG1Run'] = temp

if 'BG2' in str(StrData2 ) and 'Stopped' in (StrData2 ):    
    current = MachineStates['BG2Stop']
    temp = current + 1
    MachineStates['BG1Stop'] = temp

print (MachineStates)
Related