Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

366
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!