首页 > 解决方案 > 使用 Python 在 Excel 文件中查找和替换文件名

问题描述

基于在 xlsx 文件中使用 python openpyxl 在工作表中出现的任何单元格中查找和替换文本,我尝试执行以下操作:

文件“example.xlsx”包含我想用“'path[file.xlsm]tab1'!A5”替换“'path[file.xlsx]tab1'!A5”的单元格。我试过了:

#! 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))

但它并没有取代任何东西。我该怎么办?

标签: pythonexcelopenpyxl

解决方案


你确定你在寻找正确的文件吗?您有两个文件 example.xlsx 和 targetfile.xlsx。更改将在 targetfile.xlsx 中看到,而不是在 example.xlsx 中。

工作示例

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

推荐阅读