简体   繁体   中英

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

I'm trying to copy specific rows from Workbook 1 and append it to the existing data in Workbook 2.

Copy the highlighed rows from Workbook 1 , and append them in Workbook 2 below 'March'

So far I succeeded to copy and paste the range, but there are two problems:

1.Cells are a shifted

2.The percentage(formula) is missing, leaving only numeric values.

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)

Does anyone have any idea on how can I solve this? Any feedback/solution would help!

Thanks!

I think min_col should = 0

Range("A1").Formula (in VBA) gets the formula. Range("A1").Value (in VBA) gets the value.

So try using.formula in Python

(thanks to: Get back a formula from a cell - VBA ... if this works)

Just want to add my own solution in here.

What I did, was to iterate through the columns and apply "cell.number_format = '0%', which converts your cell value to percentage.

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%'

More info can be found in here: https://openpyxl.readthedocs.io/en/stable/_modules/openpyxl/styles/numbers.html

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