使用 openpyxl 查找匹配的字符串并填充数据
Find matching strings and populate data using openpyxl
我在 Excel 中有字典和数据。我想遍历 excel 文件中一列中的所有行,看看它是否与我字典中 'key' 中的字符串相匹配。
一旦匹配,我想将该值映射到不同的列但同一行。
例如 - 如果键在 A2
处匹配,则用字典值填充 C2
,或者如果它在 A8
处匹配,则填充 C8
.
词典示例:
my_dict = {'data1':'A','data2':'B','data3':'C'}
Excel 电子表格列:
A | B | C |
1 col1 |col2|col3|
2 data1| | |
3 apple| | |
4 pear|| | |
5 data2| | |
6 data3| | |
excel 中的所需输出:
A | B | C |
1 col1 |col2|col3|
2 data1| |A |
3 apple| | |
4 pear|| | |
5 data2| |B |
6 data3| |C |
到目前为止我尝试过的:
from openpyxl import load_workbook
wb = load_workbook('input.xlsx')
ws = wb['sheet1']
#iterate through column
for rownum in range(1, sheet.max_row + 1):
cell = ws.cell(row=rownum, column=1).value
#iterate through dictionary
for k,v in my_dict.items():
if cell == k:
#find location
print(cell.value,cell.row,cell.column,cell)
print(cell +'match')
#append value to correct cell
有人能给我指出正确的方向吗?
Openpyxl 具有用于遍历行的内置函数,iter_rows()
。可以找到它的文档 here。使用这个,解决方案非常简单。遍历行,测试第一列的值是否与字典中的键匹配。如果是,则将相应的值写入第三列。下面的代码执行此操作。
import openpyxl as op
wb = op.load_workbook("test.xlsx")
ws = wb["Sheet"]
my_dict = {'data1':'A', 'data2':'B', 'data3':'C'}
for row in ws.iter_rows(min_row=2, max_col=3):
if row[0].value in my_dict:
row[2].value = my_dict[row[0].value]
wb.save("text.xlsx")
请注意,您无需遍历字典中的每个项目(这是您的第二个 for 循环)。使用 if X in my_dict
直接循环字典中的键。
我在 Excel 中有字典和数据。我想遍历 excel 文件中一列中的所有行,看看它是否与我字典中 'key' 中的字符串相匹配。
一旦匹配,我想将该值映射到不同的列但同一行。
例如 - 如果键在 A2
处匹配,则用字典值填充 C2
,或者如果它在 A8
处匹配,则填充 C8
.
词典示例:
my_dict = {'data1':'A','data2':'B','data3':'C'}
Excel 电子表格列:
A | B | C |
1 col1 |col2|col3|
2 data1| | |
3 apple| | |
4 pear|| | |
5 data2| | |
6 data3| | |
excel 中的所需输出:
A | B | C |
1 col1 |col2|col3|
2 data1| |A |
3 apple| | |
4 pear|| | |
5 data2| |B |
6 data3| |C |
到目前为止我尝试过的:
from openpyxl import load_workbook
wb = load_workbook('input.xlsx')
ws = wb['sheet1']
#iterate through column
for rownum in range(1, sheet.max_row + 1):
cell = ws.cell(row=rownum, column=1).value
#iterate through dictionary
for k,v in my_dict.items():
if cell == k:
#find location
print(cell.value,cell.row,cell.column,cell)
print(cell +'match')
#append value to correct cell
有人能给我指出正确的方向吗?
Openpyxl 具有用于遍历行的内置函数,iter_rows()
。可以找到它的文档 here。使用这个,解决方案非常简单。遍历行,测试第一列的值是否与字典中的键匹配。如果是,则将相应的值写入第三列。下面的代码执行此操作。
import openpyxl as op
wb = op.load_workbook("test.xlsx")
ws = wb["Sheet"]
my_dict = {'data1':'A', 'data2':'B', 'data3':'C'}
for row in ws.iter_rows(min_row=2, max_col=3):
if row[0].value in my_dict:
row[2].value = my_dict[row[0].value]
wb.save("text.xlsx")
请注意,您无需遍历字典中的每个项目(这是您的第二个 for 循环)。使用 if X in my_dict
直接循环字典中的键。