如何将行高和列宽从一个 Excel 文件复制到另一个 Excel 文件

问题描述 投票:0回答:2

我正在尝试将一个 Excel 工作表从一个 Excel 工作簿复制到另一 Excel 工作簿中的另一个 Excel 工作表。

目前我可以复制所有单元格的值和格式。唯一不起作用的是列高和行高不匹配。

此外,如果存在“分组”(我不确定技术上是 Excel 中的隐藏单元格),我需要能够对它们进行分组。

有人知道如何做到这一点吗?

至少对于行高部分,我一直在试图弄清楚如何使用高度方法。最初我只是想打印出高度尺寸,看看是否可以迭代它们,但到目前为止还没有运气。

wb = openpyxl.load_workbook('Documents/test/DISCIPLINEDEQUITYATTR_EAFE_AlphaAttribution_3YRS_20180928_CLPSE.xlsx')
ws = wb.active

for i in ws.row_dimensions[2].height:
    print(i)

但我刚刚收到错误 TypeError: 'float' object is not iterable

请参阅下面的代码

import openpyxl as xl
from copy import copy


path1 = 'Documents/test/DISCIPLINEDEQUITYATTR_EAFE_AlphaAttribution_3YRS_20180928_CLPSE.xlsx'
path2 = 'Documents/test/DISCIPLINEDEQUITYATTR_EAFE_AlphaAttribution_3YRS_20180928_CLPSE_COPY.xlsx'

wb1 = xl.load_workbook(filename=path1)
ws1 = wb1.worksheets[0]

wb2 = xl.load_workbook(filename=path2)
ws2 = wb2.create_sheet(ws1.title)

for row in ws1:
    for cell in row:
        new_cell = ws2.cell(row=cell.row, column=cell.col_idx, value=cell.value)
        if cell.has_style:
            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)

wb2.save(path2)
excel python-3.x openpyxl
2个回答
1
投票

您可能想要复制行和列的尺寸。此代码与复制单元格的代码非常相似。

for idx, rd in ws1.row_dimensions.items():
     ws2.row_dimensions[idx] = copy(rd)

如果涉及样式,可能需要额外的代码。


0
投票
# Set the row height and column width of the destination cell to match the source


ws2.column_dimensions[new_cell.column_letter].width = ws1.column_dimensions[cell.column_letter].width

ws2.row_dimensions[new_cell.row].height = ws1.row_dimensions[cell.row].height
© www.soinside.com 2019 - 2024. All rights reserved.