用于替换 xlsx 单元格中的子字符串值的示例 python 代码

Sample python code to replace a substring value in an xlsx cell

尝试过的示例代码片段:

for row in range(1,sheet.max_row+1):
    for col in range(1, sheet.max_column+1):
        temp = None
        cell_obj = sheet.cell(row=row,column=col)
        temp = re.search(r"requestor", str(cell_obj.value))
        if temp:
            if 'requestor' in cell_obj.value:
                cell_obj.value.replace('requestor',
                                       'ABC')

尝试将包含值 "Customer name: requestor " 的 xlsx 单元格替换为值 "Customer name: ABC"。如何轻松实现?

我在这个 post 中找到了答案:https://www.edureka.co/community/42935/python-string-replace-not-working

替换函数没有将结果存储在同一个变量中。因此上面的解决方案:

mvar = None
for row in range(1,sheet.max_row+1):
    for col in range(1, sheet.max_column+1):
        temp = None
        cell_obj = sheet.cell(row=row,column=col)
        temp = re.search(r"requestor", str(cell_obj.value))
        if temp:
            if 'requestor' in cell_obj.value:
                mvar = cell_obj.value.replace('requestor',
                                       'ABC')
                cell_obj.value = mvar

保持简单。不是重新替换,而是搜索给定值并覆盖单元格。

下面的示例还使您能够根据需要更改 'customer name':

wb = openpyxl.load_workbook("example.xlsx")
sheet = wb["Sheet1"]

customer_name = "requestor"
replace_with = "ABC"

search_string = f"Customer name: {customer_name}"
replace_string = f"Customer name: {replace_with}"

for row in range(1, sheet.max_row + 1):
    for col in range(1, sheet.max_column + 1):
        cell_obj = sheet.cell(row=row, column=col)
        if cell_obj.value == search_string:
            cell_obj.value = replace_string

wb.save("example_copy.xlsx")  # remember that you need to save the results to the file