Search code examples
pythonexcelpywin32win32com

Python win32com - Read text in a text box to a cell?


I would like to read the text from a text box in an Excel File and save that value to a variable. The problem I am having is with the reading of the TextBox. I have tried several methods, this one showed the most promise, as it does not generate an error, but it does not elicit the desired result either. Any suggestions are appreciated. See code below.

import win32com.client as win32 
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open("C:\\users\\khillstr\\Testing\\Scripts\\Book1.xlsx")
excel.Visible = False

ws = wb.Worksheets

canvas = excel.ActiveSheet.Shapes

for shp in canvas.CanvasItems:
    if shp.TextFrame.Characters:
        print shp.TextFrame.Characters
    else:
        print "no"

Solution

  • To get the text in a textbox object on a sheet you need to use shp.TextFrame.Characters.Caption as the Characters method returns a Characters object and not a string.