查找xlsx文件中的文本,并将其替换为工作表中显示的任何单元格中的python openpyxl

2024-09-28 13:04:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前需要将一些文本:“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')

知道我在哪里搞砸了吗?任何指导都将不胜感激


Tags: 文件in文本helloforcellcolumnhi
2条回答

使用in关键字和replace method

import openpyxl

wb = openpyxl.load_workbook("sourcefile.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 = ws.cell(r,c).value
        if s != None and "hello" in s: 
            ws.cell(r,c).value = s.replace("hello","hi") 

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

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

如果需要不区分大小写的搜索/替换或更复杂的匹配,可以使用regular expression。添加import #re并使用

if s != None and re.search('hello',s,flags=re.I): 
    ws.cell(r,c).value = re.sub('hello',"Hi",s,flags=re.I)

谢谢你的解决方案。另外,当单元格上的一个值是整数而不是字符串时,我在尝试实现类似的解决方案时遇到了问题。对它的修复是使用s=str(ws.cell(r,c).value)

例如:

import openpyxl

wb = openpyxl.load_workbook("sourcefile.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 "hello" in s: 
            ws.cell(r,c).value = s.replace("hello","hi") 

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

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

相关问题 更多 >

    热门问题