Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

374
Visualizações
Iterating over pandas dataframe and saving into separate sheets in xlxs file

I'm iterating over a pandas dataframe during and carry out and operation to obtain the information (excel sheet number) for saving the appropriate excel sheet like this:

from opnepyxl.utils.dataframe import dataframe_to_rows

for i,data in df.iterows:
    sheet=data['SheetNo']

    #Create excel writer
    writer=pd.Excelwriter('output.xlxs')

    # write dataframe to excelsheet
    data.to_excel(writer, sheet)

    #save the excel file
    writer.save()

Dataframe:

ID  SheetNo setting
2304    2   IGV5
2305    3   IGV2
2306    1   IGV6
2307    2   IGV2
2308    1   IGV1

What I wanted was for data to go into each of the created 'SheetNo' of the excel file, instead the the previous sheet is being overwritten by the following one, and you can only see the last sheet number.

What can I do to make this code work? Any other approach apart from mine above will be welcome.

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

the python code is below. Note that:

  1. Assumption is that there is already an output.xlsx file in same dir that this code runs
  2. It will search for worksheet names with the SheetNo column. If not available in the file, it will create a new worksheet/tab with that name and add the header row 3.The program will then add each row (append) to the sheet
  3. Once all data in DF is added, it will save file back to same name
  4. You can run this as many times as you want, it will keep adding new sheets or appending to existing sheets.
import pandas as pd
from openpyxl import load_workbook

data = {'ID': [2304,2305,2306,2307,2308],
'SheetNo': [2,3,1,2,1],
'setting': ['IGV5', 'IGV2', 'IGV6', 'IGV2', 'IGV1']}

df = pd.DataFrame(data)
headers = ['ID','SheetNo','setting']

FilePath = 'output.xlsx' #ASSUMPTON - File already exists
wb = load_workbook(FilePath)

for sheet in df.SheetNo.unique(): 
    if str(sheet) in wb.sheetnames: #If sheet in excel file
        ws = wb[str(sheet)]
    else:
        ws = wb.create_sheet(title=str(sheet)) #Create New sheet is not present
        ws.append(headers) #New sheet = Need header, else not required
    i =0
    j = 0
    for row in ws.iter_rows(min_row=ws.max_row+1, max_row=ws.max_row+len(df[df.SheetNo == sheet]), min_col=1, max_col=3):
        for cell in row:
            cell.value = df[df.SheetNo == sheet].iloc[i,j]
            j = j + 1
        j=0
        i= i + 1
wb.save('output.xlsx')

Output excel after one run of the code

enter image description here

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda