简体   繁体   English

如何在Excel工作表中查找值,然后使用openpyxl在同一行的不同单元格中写入另一个值

[英]How to find a value in excel sheet and then write another value in a different cell in the same row with openpyxl

I am trying to search for a specific value in rows of an excel file. 我正在尝试在Excel文件的行中搜索特定值。 Upon finding a matching value, I would like to write another value in the column next to the found value in the same row. 找到匹配的值后,我想在同一行中找到的值旁边的列中写入另一个值。

For instance, if I am looking for the word "test" and find it in cell A3, I would then want to print a specified value, say 6, in cell B3. 例如,如果我要查找单词“ test”并在单元格A3中找到它,那么我想在单元格B3中打印一个指定的值,例如6。

If it makes a difference, I do anticipate only having to search the A column for the value and always printing the other value to the B column in the same row. 如果有所不同,我确实希望只需要在A列中搜索值,并始终将其他值打印到同一行的B列中。

Here is the code I have so far. 这是我到目前为止的代码。

wb = openpyxl.load_workbook(path)
ws = wb.get_sheet_by_name('Sheet')
for row in ws.iter_rows():
    for cell in row:
        if cell.value == "test":
            ws.cell(row=cell, column=2).value = 6
wb.save(path)

Any help would be greatly appreciated! 任何帮助将不胜感激!

ws.cell(row=cell, column=2).value = 6

应该

 ws.cell(row=cell, column=2, value=6)

Change this line 更改此行

 ws.cell(row=cell, column=2).value = 6

to

 ws.cell(row=cell.Row, column=2).value = 6

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 openpyxl按值查找单元格或行 - openpyxl find cell or row by value 如何将 Pandas Dataframe 从 python 水平写入 Excel 表中,连续列打开 - How to write Pandas Dataframe Horizontally in to Excel sheet from python openpyxl (elements in same row, consecutive columns) 如何从从另一张表链接的单元格中获取值,openpyxl - How to get value from cell which is linked from another sheet, openpyxl 当使用 Openpyxl 的行上的单元格中有字符串值时,如何突出显示 Excel 行? - How to highlight an Excel row when there is a string value in a cell on a row using Openpyxl? Excel:如何在包含字符串的列中查找单元格并在另一列行中返回单元格的值? - Excel: How to find cell in a column that contains a string and return value of a cell in another column of row? Excel 使用 openpyxl 搜索单元格值并删除行 - Excel search for cell value and delete row using openpyxl 如何获取单元格的值而不是 <Cell 'Sheet1'.A2> &#39;与openpyxl - How to get the value of a cells instead of <Cell 'Sheet1'.A2>' with openpyxl Openpyxl - 如何引用另一张纸上的单元格 - Openpyxl - How to reference cell on another sheet Openpyxl:如何检查单元格是否包含特定值后如何复制行 - Openpyxl: How to copy a row after checking if a cell contains specific value OpenPyXL-如果cell.value为None则如何跳过行 - OpenPyXL - How to skip row if cell.value is None
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM