Home > other >  If condition based on cell value in excel using Openpyxl
If condition based on cell value in excel using Openpyxl

Time:06-30

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.

enter image description here

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

enter image description here

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.

CodePudding user response:

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.

CodePudding user response:

So, a simple solution and a more complicated one:

enter image description here

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

CodePudding user response:

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

enter image description here

  • Related