简体   繁体   中英

If condition based on cell value in excel using Openpyxl

There are two excel files, where the data on condition should be appended to another excel file.

CONDITION: If Any value in Column A is equal to 'x' then it should get value from col B and get it appended directly to col A/B in excel file 2.

The below table is present in Excel File 1.

在此处输入图像描述

The below should be the output... which is in Excel file 2.

在此处输入图像描述

Am new to this.. please help with this code, and preferably if code is done using "Openpyxl", it would be much helpful !

Thanks in advance.

A slight improvement on Redox's solution:

import openpyxl
#Open Input File open (file1)
wb1 = openpyxl.load_workbook('file1.xlsx')
ws1 = wb1['Sheet1']

wb2 = openpyxl.Workbook()
ws2 = wb2.active
ws2.append(["Base", "A/B"])

for row in ws1.iter_rows(min_row=2, max_col=3, values_only=True):
    base, a, b = row
    if a != "x":
        new_row = [base, a]
    else:
        new_row = [base, b]
    ws2.append(new_row)

Ideally you should also check that the third column has a valid value.

So, a simple solution and a more complicated one:

在此处输入图像描述

Then between files you can use a link or index() or indirect().

To do this using python-openpyxl, you can use the below code... added comments so it is easy to understand... hope this helps. Let me know in case of questions.

The python code

import openpyxl
#Open Input File open (file1)
wb1 = openpyxl.load_workbook('file1.xlsx')
ws1 = wb1['Sheet1']
#Create new file for Output (file2)
wb2 = openpyxl.Workbook()
ws2 = wb2.active
#Add header to output file
ws2.cell(row=1,column=1).value = "BASE"
ws2.cell(row=1,column=2).value = "A/B"

# Iterate through each line in input file from row 2 (skipping header) to last row
for row in ws1.iter_rows(min_row=2, max_row=ws1.max_row, min_col=1, max_col=3):
    for col, cell in enumerate(row):
        if col == 0: #First column, write to output
            ws2.cell(cell.row, col+1).value = cell.value
        elif col == 1:
            if cell.value != "X": #2nd column, write to output if not X
                ws2.cell(cell.row, col+1).value = cell.value
        else: #2nd column, write 3rd column if X
                ws2.cell(cell.row, col+1).value = ws1.cell(cell.row, col+2).value

wb2.save('file2.xlsx')

Output excel after running

在此处输入图像描述

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