首页 > 解决方案 > 新工作表的值

问题描述

我已经开始使用 openpyxl,而且我很喜欢它。

目标是在条件为真时将所有行复制到新工作表,我的代码可以工作,但不是根据条件将值复制到新工作表,而是将所有值复制到同一个工作表。

PS:请原谅我的英文

 import openpyxl as excel

 def trata_excel(nomeficheiro):
    # variable declaration
    livro = excel.load_workbook(nomeficheiro)
    folha = livro['Folha1']
    # it stores the headers and respective column
    cabeçalhos = {}
    alvos = []

    # i'm retriving all the headers from the column
    for coluna in range(1,folha.max_column +1):
        celula = folha.cell(row=1, column=coluna)
        # And add it to the dictionary
        cabeçalhos.update({celula.value:coluna})

    # checking if header "Alvo" in the dictionary
    if "Alvo" in cabeçalhos:
        # Getting the column number for the header Alvo
        coluna_alvo = cabeçalhos["Alvo"]
        # check all the rows to see 
        for linha in range(2,folha.max_row +1):
            # How many Alvo
            celula_alvo = folha.cell(linha,coluna_alvo)
            # Check if the Alvo is not already in the list
            if celula_alvo.value not in alvos:
                #if not i'm adding it
                alvos.append(celula_alvo.value)
            else:
                return "Não encontrei a coluna referente a 'Alvo"

    #checking whats the  "Tipo de Produto" column number
    coluna_produto = cabeçalhos["Tipo de Produto"]

    # i'm going to check  for each Alvo
    for alvo in alvos:
        # Creating a new sheet with Alvo name
        nova_folha = livro.create_sheet(str(alvo))
        # for each alvo going to see each line
        nova_linha = 1 # variable to add all the lines in consecutive line
        for linha in range(2,folha.max_row+1):
            produto = folha.cell(linha, coluna_produto)
            # here i select the values that i want
            if (alvo == celula_alvo.value and produto.value =="Voz" or 
             alvo == celula_alvo.value and produto.value == "SMS" or
             alvo == celula_alvo.value and produto.value=="MMS"):
                nova_linha += 1
                for coluna in range(1, folha.max_column + 1):
                    valor = folha.cell(row=linha, column=coluna).value
                    livro[str(alvo)].cell(row=nova_linha,column=coluna, value= valor)

        livro.save("novo.xlsx")

    #print(cabeçalhos)
    # just to control
    print(alvos)

标签: python-3.xopenpyxl

解决方案


推荐阅读