How to combine multiple excel sheets from different files into one file

Each source file contains only one sheet. All I want is to combine these sheets into one file. I guess I have to use win32com.

Does anyone know how?

Update: The sheets to be merged have advanced conditional formatting that I would like to keep. The following code could only combine them with all the lost conditionally formatted data.

from openpyxl import load_workbook, Workbook
import os

fwb = Workbook()

wb = load_workbook('CM1.xlsx')
ws1 = wb.active
wb = load_workbook('CM2.xlsx')
ws2 = wb.active
wb = load_workbook('CM3.xlsx')
ws3 = wb.active

fwb.add_sheet(ws1)
fwb.add_sheet(ws2)
fwb.add_sheet(ws3)

fwb.save('CM.xlsx')
+4
source share
2 answers

Thanks to both of you! After taking your advice and trying for 5 minutes, worked!

import win32com.client as win32
import os

excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Add()

for f in [os.path.join(os.getcwd(), "CM1.xlsx"), os.path.join(os.getcwd(), "CM2.xlsx")]: 
    w = excel.Workbooks.Open(f) 
    w.Sheets(1).Copy(wb.Sheets(1))

wb.SaveAs(os.path.join(os.getcwd(), "CM.xlsx"))
excel.Application.Quit()
+1
source

this inserts sheet 1 from to_copy into sheet 1 of the empty book

empty_wb = xl.Workbooks.Open(util.getTestRessourcePath("emptyWorkbook.xlsx"))
tocopy_wb = xl.Workbooks.Open(util.getTestRessourcePath("toCopy.xls"))

tocopy_wb.Sheets(1).Cells.Copy()
empty_wb.Sheets(1).Paste(empty_wb.Sheets(1).Range("A1"))
0
source

Source: https://habr.com/ru/post/1525711/


All Articles