简体   繁体   English

在它出现在工作表中的任何单元格中使用 python openpyxl 查找和替换 xlsx 文件中的文本

[英]Find and Replace text in xlsx file with python openpyxl in whichever cell it appear in within sheet

I currently need to replace some text: "hello" with "hi" wherever it may appear in an xlsx file(s) [think search and replace].我目前需要在 xlsx 文件中出现的任何地方替换一些文本:“hello”与“hi”[思考搜索和替换]。

Following the logic from Find and replace in cells from excel in python , I see that I am able to successfully open the source xlsx file, and then finally save to a new xlsx file, however my text never gets replaced.按照在 python 中的 excel 中的单元格中查找和替换的逻辑,我看到我能够成功打开源 xlsx 文件,然后最后保存到一个新的 xlsx 文件,但是我的文本永远不会被替换。

Note: my text may appear in the beginning, middle, or end of a string and the cell in which it appears may vary from one xlsx file to the next.注意:我的文本可能出现在字符串的开头、中间或结尾,并且它出现的单元格可能因一个 xlsx 文件而异。

Here is my code currently:这是我目前的代码:

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

Any idea where I am messing this up?知道我在哪里搞砸了吗? Any guidance would be greatly appreciated!任何指导将不胜感激!

Use in keyword and replace method in关键字和替换方法中使用

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

If you want case insensitive search/replace or more complicated matching you can use a regular expression .如果您想要不区分大小写的搜索/替换或更复杂的匹配,您可以使用正则表达式 Add import #re and use添加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)

Thanks for this solution.感谢您提供此解决方案。 Also, I ran into issue when trying to implement similar solution when one of the values on the cell was integer instead of string.此外,当单元格上的值之一是整数而不是字符串时,我在尝试实现类似的解决方案时遇到了问题。 The fix to it was the using s = str(ws.cell(r,c).value)解决方法是使用 s = str(ws.cell(r,c).value)

eg:例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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