Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

367
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda