Merging multiple XLSM templates to Python

36 Views Asked by At

For a project that a i am trying to move from RPA to completly Python i need to merge a main XLSM template with multiple copies of another template, but i am already stuck on the first step. Merging the two. For is my code see below. I'm keeping styling from my first template, but not of the second one (path2) because it crashes when i change values_only to false(), giving me ValueError: Cells cannot be copied from other worksheet Is it possible to keep the styling of path2 ? Or am i trying the impossible?

import openpyxl as xl

# Load the first workbook (destination workbook)
path1 = 'C:\\Users\\bob\\\Documents\\PythonTest\\workbook1.xlsm'
destination_wb = xl.load_workbook(filename=path1, read_only=False, keep_vba=True)

# Load the second workbook (source workbook)
path2 = 'C:\\Users\\bob\\\Documents\\PythonTest\\workbook2.xlsm'
source_wb = xl.load_workbook(filename=path2, read_only=True, keep_vba=True)

# Iterate over each sheet in the source workbook
for source_sheet in source_wb.sheetnames:
    # Get the source worksheet
    source_ws = source_wb[source_sheet]

    # Create a new sheet in the destination workbook
    destination_ws = destination_wb.create_sheet(title=source_sheet)

    # Copy the values, formatting, and styling from the source worksheet to the destination worksheet
    for row in source_ws.iter_rows(values_only=True):
        destination_ws.append(row)

    # Copy the source worksheet's formatting and styles to the destination worksheet
    destination_ws.sheet_format = source_ws.sheet_format
    destination_ws.sheet_properties = source_ws.sheet_properties
    destination_ws.sheet_view = source_ws.sheet_view

    for row in source_ws.iter_rows(min_row=1, min_col=1, max_row=source_ws.max_row, max_col=source_ws.max_column):
        for cell in row:
            destination_ws[cell.coordinate]._style = cell._style

# Save the modified destination workbook
destination_wb.save('C:\\Users\\User\\\Documents\\PythonTest\\outfile.xlsm')
0

There are 0 best solutions below