[英]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:基于使用 python openpyxl 在 xlsx 文件中查找和替换文本,无论它出现在工作表中的哪个单元格中,我都尝试执行以下操作:
The file "example.xlsx" contains cells where I want to replace "'path[file.xlsx]tab1'.A5" by "'path[file.xlsm]tab1':A5".文件“example.xlsx”包含我想用“'path[file.xlsm]tab1':A5”替换“'path[file.xlsx]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我正在使用 windows 并且当我在保存时指定文件路径时,它只能覆盖最初打开的工作簿,所以如果你想覆盖打开的文件,只需修改倒数第二行即可
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我可以在不指定路径的情况下保存一个新文件(就像你正在做的那样,打开
example.xlsx
并保存targetfile.xlsx
),但由于某种原因要覆盖现有文件,你需要一个路径
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.
您有两个文件 example.xlsx 和 targetfile.xlsx。 The changes will be seen in targetfile.xlsx not in example.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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.