我目前需要将一些文本:“hello”替换为“hi”,无论它出现在xlsx文件中的任何位置[思考搜索和替换]
按照Find and replace in cells from excel in python中的逻辑,我看到我能够成功地打开源xlsx文件,然后最终保存到一个新的xlsx文件,但是我的文本从未被替换
注意:我的文本可能出现在字符串的开头、中间或结尾,并且它出现的单元格可能因xlsx文件而异
这是我目前的代码:
wb = openpyxl.load_workbook(sourcefile.xlsx')
wb.sheetnames
sheet = wb["sheet1"]
amountOfRows = sheet.max_row
amountOfColumns = sheet.max_column
for i in range(amountOfColumns):
for k in range(amountOfRows):
cell = str(sheet[get_column_letter(i+1)+str(k+1)].value)
if( str(cell[0]) == "hello"):
newCell = "hi"+cell[1:]
sheet[get_column_letter(i+1)+str(k+1)]=newCell
wb.save('targetFile.xlsx')
知道我在哪里搞砸了吗?任何指导都将不胜感激
使用
in
关键字和replace method如果需要不区分大小写的搜索/替换或更复杂的匹配,可以使用regular expression。添加
import #re
并使用谢谢你的解决方案。另外,当单元格上的一个值是整数而不是字符串时,我在尝试实现类似的解决方案时遇到了问题。对它的修复是使用s=str(ws.cell(r,c).value)
例如:
相关问题 更多 >
编程相关推荐