Reg: массив в Python openpyxl

#python #arrays #excel #openpyxl

#python #массивы #excel #openpyxl

Вопрос:

Я пытаюсь прочитать и записать некоторые данные в Excel, используя Python с модулем Openpyxl. Вот код, над которым я работаю. Я не смог справиться с массивами. Немного сложно объявить много переменных. Может ли кто-нибудь помочь мне в этом отношении, пожалуйста…

 #---------------------------------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)
 

Заранее благодарю вас.

С уважением

Ответ №1:

Я полагаю, что вы ищете словарь Python. Вот как вы могли бы использовать словарь для подсчета значений.

 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)