Openpyxl - 将单元格范围(带公式)从工作簿复制到另一个工作簿

Openpyxl - Copy range of cells(with formula) from a workbook to another

我正在尝试从工作簿 1 复制特定行并将其附加到工作簿 2 中的现有数据。

复制突出显示的行 Workbook 1, 并将它们附加到 'March'

下面的 Workbook 2

至此复制粘贴范围成功,但是有两个问题:

1.Cells 是移位的

2.The百分比(公式)缺失,只留下数值。

See Result here

import openpyxl as xl

source = r"C:\Users\Desktop\Test_project_20200401.xlsx"
wbs = xl.load_workbook(source)
wbs_sheet = wbs["P2"] #selecting the sheet

destination = r"C:\Users\Desktop\Try999.xlsx"
wbd = xl.load_workbook(destination)
wbd_sheet = wbd["A3"] #select the sheet

row_data = 0

for row in wbs_sheet.iter_rows():
    for cell in row:
        if cell.value == "Yes":
            row_data += cell.row

for row in wbs_sheet.iter_rows(min_row=row_data, min_col = 1, max_col=250, max_row = row_data+1):
    wbd_sheet.append((cell.value for cell in row))            


wbd.save(destination)

有人知道我该如何解决这个问题吗? 任何 feedback/solution 都会有所帮助!

谢谢!

我觉得min_col应该=0

Range("A1").Formula (in VBA) 得到公式。 Range("A1").Value(inVBA)获取值

所以尝试在 Python

中使用 .formula

(感谢:Get back a formula from a cell - VBA ...如果可行)

只想在这里添加我自己的解决方案。

我所做的是遍历列并应用“cell.number_format = '0%',这会将您的单元格值转换为百分比。

for col in ws.iter_cols(min_row=1, min_col=2, max_row=250, max_col=250):
    for cell in col:
        cell.number_format = '0%'

更多信息可以在这里找到: https://openpyxl.readthedocs.io/en/stable/_modules/openpyxl/styles/numbers.html