Home > Enterprise >  How to find cell in a column that contains a string and return value of a cell in another of row?
How to find cell in a column that contains a string and return value of a cell in another of row?

Time:10-29

If the cell contains "external" from the C column then copy cell "good" from the D column, into the E column, in the rows where the A column contains 003.

Below are two images (before and after) in excel.

Before:

enter image description here

After:

enter image description here

I tried to find a correct script but it did not work out. It needs to be changed to "row" and "column" where I put "???" :

import openpyxl
from openpyxl import load_workbook
wb_source = openpyxl.load_workbook("path/file.xlsx")
sheet = wb_source['Sheet1']
x=sheet.max_row
y=sheet.max_column

for r in range(1, x 1) :
   for j in range(1, y 1):
       copy(sheet.cell(row= ???, column=???)
         if str(copy.value)=="external":
         sheet.??
         break
wb_source.save("path/file2.xlsx")

How should they be added (row and column)?

CodePudding user response:

  1. Read the entire sheet.
  2. Create a dictionary for the external products
  3. Write back to Excel.

Try:

import openpyxl
wb = openpyxl.load_workbook("file1.xlsx")
ws = wb['Sheet1']

data = list()
for r, row in enumerate(ws.iter_rows()):
    data.append([cell.value for c, cell in enumerate(row)])
mapper = {l[0]: l[-1] for l in data if l[2]=="external"}

for r, row in enumerate(ws.iter_rows()):
    if ws.cell(r 1, 1).value in mapper:
        ws.cell(r 1, 5).value = mapper[ws.cell(r 1, 1).value]
wb.save("file2.xlsx")
  • Related