简体   繁体   中英

How to looping copy data from one excel sheet to another with same filename with pandas

I have 5 folder which contain 50 excel file with same file name. I want to create loop to join that excel, but in different sheet. Let's say the first folder named Task, second one attendance, performance, course, and the last one is misc. The folder name = sheet name. For the first time, i just to have joining 10 excel files in 2 folders. But it getting more. To join the excel files in task folder with excel files in attendance folder, i'm using this code and do all of those one by one. But i get so overwhelmed if i do all of those things one by one. Can someone help me to create a loop by this code to get the output like expected result?

expected result

Thank you!

import pandas as pd
import glob
from openpyxl import load_workbook

#By task no prefix
path_task = r"C:\Users\runner\Documents\reportschool\Task\SocialA2.xlsx"

book = load_workbook(path_task)
writer = pd.ExcelWriter(path_task, engine = 'openpyxl', mode = 'a')
writer.book = book

#joined
attendance = pd.read_excel(r"C:\Users\runner\Documents\reportschool\Attendances\SocialA2.xlsx")

attendance.to_excel(writer, sheet_name = 'Attendance', index = False)
writer.save()
writer.close()

If you know names of folders then put them on list and use for -loop

all_names = ['Attendance', 'Performance', 'Course', 'Misc']

for name in all_names:
    path = r"C:\Users\runner\Documents\reportschool\{}\SocialA2.xlsx".format(name)
    data = pd.read_excel(path)
    data.to_excel(writer, sheet_name=name, index=False)

And later you can use glob to get folders and extract names to list all_names using string functions, or os.path functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM