Python Forum
Win32Com: How to Execute Find & Replace?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Win32Com: How to Execute Find & Replace?
#1
I want to replace the contents in my Excel cells. I tried the below 2 codes. But both doesn't work

Thanks

Code 1 :Same Error when I tried with Find or Replace. AttributeError: 'function' object has no attribute 'Execute'
import win32com.client as w3c

xl=w3c.DispatchEx("Excel.Application")
wb=xl.Workbooks.Open(Filename=file_location, ReadOnly=False, UpdateLinks=0, IgnoreReadOnlyRecommended=True)
ws=wb.Worksheets("Sheet1")
ws.Activate

ws.Cells.Find("'*[Test.xlsx]Sheet4'")
ws.Cells.Replace("'Sheet4'")
#ws.Cells.Find.Execute
#ws.Cells.Replace.Execute

wb.Close(SaveChanges=True)
del wb     
Code 2 No Error but no replace occurred.

l=ws.Cells.Find (What="'*[PYTHON_Use_ONLY.xlsx]Cutoffs'", LookAt=w3c.constants.xlPart, SearchOrder=w3c.constants.xlByRows, MatchCase=False,
        SearchFormat=False)

print(l) --> -2146826246

j=ws.Cells.Replace (What="'Cutoffs'", LookAt=w3c.constants.xlPart, SearchOrder=w3c.constants.xlByRows, MatchCase=False,
        SearchFormat=False, ReplaceFormat=False, FormulaVersion=w3c.constants.xlReplaceFormula2)

print(j) --> True
Reply
#2
You can do this with pyexcel and extension pyexcel-xlsx

# if not already installed:
# pip install pyexcel
# pip install pyexcel-xlsx
#
import pyexcel
import os

# set starting path same as script
os.chdir(os.path.abspath(os.path.dirname(__file__)))

sheet = pyexcel.get_sheet(file_name="TestData.xlsx")

print(f"Value prior to change: {sheet[2,1]}")
sheet[2,1] = "New value"
print(f"Value after change: {sheet[2,1]}")

# save as new xlsx sheet
sheet.save_as("NewData.xlsx")
Example output (my random spreadsheet)
Output:
Value prior to change: Belvidere Value after change: New value
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020