Search code examples
python-3.6xlsxpdfkitpython-re

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


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 ?


Solution

  • 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