简体   繁体   中英

Find and replace file name in Excel file using Python

based on Find and Replace text in xlsx file with python openpyxl in whichever cell it appear in within sheet I tried to do the following:

The file "example.xlsx" contains cells where I want to replace "'path[file.xlsx]tab1'.A5" by "'path[file.xlsm]tab1':A5". I tried:

#! python3
import openpyxl

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

i = 0
for r in range(1,ws.max_row+1):
for c in range(1,ws.max_column+1):
    s = str(ws.cell(r,c).value)
    if s != None and "xlsx" in s: 
        ws.cell(r,c).value = s.replace("xlsx","xlsm") 

        print("row {} col {} : {}".format(r,c,s))
        i += 1

wb.save('targetfile.xlsx')
print("{} cells updated".format(i))

But it did not replace anything. What shall I do?

I am using windows and it only works to overwrite the originally opened workbook when i specify a file path on the save, so simply modifying penultimate line to this works if you want to overwrite the opened file

wb.save(".\\example.xlsx")

I can save a new file (as you are doing, opening example.xlsx and saving targetfile.xlsx ) without specifying a path but for some reason to overwrite an existing file you need to have a path

I did the following:

#! python3
import openpyxl

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

i = 0
for r in range(1,ws.max_row+1):
    for c in range(1,ws.max_column+1):
        s = str(ws.cell(r,c).value)
        if s != None and "xlsx" in s:
        s=s.replace("xlsx","xlsm") 
        ws.cell(r,c).value = s
        print("row {} col {} : {}".format(r,c,s))
        i += 1

wb.save('targetfile.xlsx')
print("{} cells updated".format(i))

But it did not replace anything.

Are you sure you're looking in the correct file? You have two files example.xlsx and targetfile.xlsx. The changes will be seen in targetfile.xlsx not in example.xlsx.

Working Example

import openpyxl

wb = openpyxl.load_workbook("mydoc.xlsx")
ws = wb['Sheet1']
i = 0
for r in range(1,ws.max_row+1):
    for c in range(1,ws.max_column+1):
        s = str(ws.cell(r,c).value)
        if "xlsx" in s: 
            ws.cell(r,c).value = s.replace("xlsx","xlsm") 

            print("row {} col {} : {}".format(r,c,s))
            i += 1

wb.save('mycode.xlsx')
print("{} cells updated".format(i))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM