简体   繁体   中英

Openpyxl - Appending data from an Excel workbook to another

I would like to get a specific row from Workbook 1 and append it after the existing data in Workbook 2.

The code that I tried so far can be found down below:

import openpyxl as xl
from openpyxl.utils import range_boundaries
min_cols, min_rows, max_cols, max_rows = range_boundaries('A:GH')

#Take source file
source = r"C:\Users\Desktop\Python project\Workbook1.xlsx"
wb1 = xl.load_workbook(source)
ws1 = wb1["P2"] #get the needed sheet


#Take destination file
destination = r"C:\Users\Desktop\Python project\Workbook2.xlsx"
wb2 = xl.load_workbook(destination)
ws2 = wb2["A3"] #get the needed sheet


row_data = 0

#Get row & col position and store it in row_data & col_data
for row in ws1.iter_rows():
    for cell in row:
        if cell.value == "Positive":
            row_data += cell.row


for row in ws1.iter_rows(min_row=row_data, min_col = 1, max_col=250, max_row = row_data):
    ws2.append((cell.value for cell in row[min_cols:max_cols]))  


wb2.save(destination)
wb2.close()

But when I use the above mentioned code, I get the result but with a shift of 1 row. I want the data that is appended to row 8, to be on row 7, right after the last data in Workbook 2. (See image below)

Workbook 2

Does anyone got any feedback? Thanks!

I found the solution and will post it here in case anyone will have the same problem. Although the cells below looked empty, they had apparently, weird formatting. That's why the Python script saw the cells as Non-empty and appended/shifted the data in another place(the place where there was no formatting).

The Solution would be to format every row below your data as empty cells. (Just copy a range of empty cells from a new Workbook and paste it below your data)

Hope that helps; ;)

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