如何将不同文件中的多个Excel表合并到一个文件中

时间:2021-02-27 20:23:24

Each source file contains only one sheet. All I want is to combine these sheets into a single file. I suppose I'll have to use win32com.

每个源文件只包含一个工作表。我要做的就是把这些表格合并成一个文件。我想我得用win32com。

Does anyone know how?

有人知道吗?

Update: the sheets to be combined have extensive conditional formatting that I'd like to keep. The following code could only combine them with all conditionally formatting information lost.

更新:要合并的表具有广泛的条件格式,我希望保留这些格式。下面的代码只能将它们与所丢失的所有条件格式信息组合在一起。

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')

2 个解决方案

#1


1  

Thank you both! After taking your advice and trying for 5 minutes, the following worked!

谢谢你们俩!在听取了你的建议并尝试了5分钟后,以下方法奏效了!

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()

#2


0  

this will paste sheet 1 ot to_copy to sheet 1 of emptyWorkbook

这将把第1页粘贴到空白工作簿的第1页

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"))

#1


1  

Thank you both! After taking your advice and trying for 5 minutes, the following worked!

谢谢你们俩!在听取了你的建议并尝试了5分钟后,以下方法奏效了!

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()

#2


0  

this will paste sheet 1 ot to_copy to sheet 1 of emptyWorkbook

这将把第1页粘贴到空白工作簿的第1页

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"))