Search code examples
pythonexcelcomwin32com

Adding an Excel Textbox with win32com


I am trying to add an Excel Textbox to a worksheet... the typical shortcut I use in the Excel GUI is Alt+N X and then click where I want the Textbox; however, I don't have access to the COM browser, which leaves me guessing where Microsoft hid the Textbox API under Python's win32com...

from win32com import client

excel=client.Dispatch("Excel.Application")
excel.Visible=True
book=excel.Workbooks.Open("c:/Users/dpennington/Desktop/Blank.xls", False, 
    True)
sheet=book.Worksheets(2)

How would I add a textbox (i.e. in the Excel GUI: Alt+N X), using Python's win32com api? (Specific positioning in the worksheet is up to you...)


Solution

  • Use the AddTextbox method of the Shapes object:

    import win32com.client as client
    
    xl = client.Dispatch("Excel.Application")
    xl.Visible = True
    wb = xl.Workbooks.Open("c:/1temp/badacres.xls")
    ws = wb.Sheets(1)
    
    tb = ws.Shapes.AddTextbox(1, 570, 45, 171, 80)
    tb.TextFrame2.TextRange.Characters.Text = 'This is a great big test.'
    

    You can find more on the AddTextbox method here.