简体   繁体   中英

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

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:

在此处输入图片说明

After:

在此处输入图片说明

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)?

  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")

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