-2

Sample code snippet tried:

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

Trying to replace from an xlsx cell containing value "Customer name: requestor " with value "Customer name: ABC" .How can this be achieved easily ?

4

2 回答 2

-1

I found my answer in this post:https://www.edureka.co/community/42935/python-string-replace-not-working

The replace function doesn't store the result in the same variable. Hence the solution for above:

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
于 2020-04-06T11:37:08.160 回答
-1

Just keep it simple. Instead of re and replace, search for the given value and override the cell.

The example below also gives you the ability to change 'customer name' if needed:

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
于 2020-04-13T04:16:22.360 回答