Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
137 views
in Technique[技术] by (71.8m points)

python - Copying data from multiple excel files to multiple sheets of a single excel file

I am trying to copy data from multiple excel files into multiple sheets of a single excel file. But I am not able to figure out how to change the active sheet of the master excel so that I can copy the new data into a new sheet. I can do this by repeating the code multiple times but that is not feasible. Also the below code is one of the approaches that I tried but this just rewrites data into the same sheet, so if you can help me to change the active sheet of the master excel or if you have a better solution that would be helpful, preferred in openpyxl instead of pandas or xlrd

`import openpyxl as xl
    excel1 = "excel1.xlsx"
    excel2 = "excel2.xlsx"
    masterexcel = "Master excel.xlsx"
    files = [excel1, excel2]
    for file in files:
        wb1 = xl.load_workbook(file)
        ws1 = wb1.worksheets[0]

        filename1 = masterexcel
        wb2 = xl.load_workbook(masterexcel)
        ws2 = wb2.worksheets[0] #this is to change the active sheet
        wb2.active = 0
    
        mr = ws1.max_row
        mc = ws1.max_column
        
        for i in range(1, mr + 1):
            for j in range(1, mc + 1):
               
                c = ws1.cell(row=i, column=j)
               
                ws2.cell(row=i, column=j).value = c.value
      
        wb2.save(str(masterexcel))`
question from:https://stackoverflow.com/questions/66066454/copying-data-from-multiple-excel-files-to-multiple-sheets-of-a-single-excel-file

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...