繁体   English   中英

Python/openpyxl - 有没有办法将工作表从一个工作簿复制到另一个具有所有属性的工作簿(精确副本)

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

我已经研究了这个论坛上几个类似的讨论主题,并尝试了一些推荐的东西,但我无法复制源工作表的所有属性。 这是我的代码,我看到列宽和其他一些事情没有解决。 如果 openpyxl 实现了 function 来复制具有所有属性的工作表,那就太好了。

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

这似乎可以完成工作 - 设置列宽:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM