简体   繁体   中英

Python/openpyxl - Is there a way to copy a worksheet from one workbook to another with all properties (exact copy)

I have researched through several similar threads of discussion on this forum and tried several things recommended, but I am not able to get all properties of the source worksheet copied over. Here's my code and I see that column widths and a few other things are not coped over. Would have been great if openpyxl implemented a function to copy a worksheet with all its attributes.

def copy_worksheet(src_xl, dest_xl, src_ws, dest_ws):
    import openpyxl as xl
    from copy import copy

    # opening the source excel file 
    wb1 = xl.load_workbook(src_xl)
    sheet_names = wb1.sheetnames
    index = sheet_names.index(src_ws)
    ws1 = wb1.worksheets[index] 

    # opening the destination excel file
    wb2 = xl.load_workbook(dest_xl)
    sheet_names = wb2.sheetnames
    try:
        index = sheet_names.index(dest_ws)
    except:
        ws2 = wb2.create_sheet(dest_ws)
    else:
        ws2 = wb2.worksheets[index] 

    # calculate total number of rows and  
    # columns in source excel file 
    mr = ws1.max_row 
    mc = ws1.max_column 

    # copying the cell values from source  
    # excel file to destination excel file 
    for i in range (1, mr + 1): 
        for j in range (1, mc + 1): 
            # reading cell value from source excel file 
            c = ws1.cell(row = i, column = j)
            cell = c

            # writing the read value to destination excel file 
            ws2.cell(row = i, column = j).value = c.value
            new_cell = ws2.cell(row = i, column = j)

            new_cell.font = copy(cell.font)
            new_cell.border = copy(cell.border)
            new_cell.fill = copy(cell.fill)
            new_cell.number_format = copy(cell.number_format)
            new_cell.protection = copy(cell.protection)
            new_cell.alignment = copy(cell.alignment)

    # saving the destination excel file 
    wb2.save(str(dest_xl))

This seems to do the job - to set the column widths:

from openpyxl.utils import get_column_letter
for i in range(ws1.max_column):
    ws2.column_dimensions[get_column_letter(i+1)].width = ws1.column_dimensions[get_column_letter(i+1)].width

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