Search code examples
python-3.xexcelwin32com

Auto size comment box


I am using win32com module to write an excel file. One of the tasks I am attempting is to add comments to a cell and auto adjust the comment box size. If the size is not adjusted then part of the comments are not visible when one hovers over the cell. This is what I have so far:

from win32com.client import Dispatch
import os

dirpath = os.path.dirname(os.path.realpath(__file__))
outputfile = 'ExcelTest.xlsx'
excel = Dispatch("Excel.Application")

wb = excel.Workbooks.Add()
ws = wb.Worksheets('Sheet1')
ws.Name = 'Test'

ws.Cells(1, 1).Value = 'Hi'
rng = ws.Range(ws.Cells(1, 1), ws.Cells(1, 1))
cmt = rng.AddComment('Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum')
cmt.Shape.TextFrame.Characters().Font.Bold = False
cmt.ShapeRange.ScaleWidth = 3.0
cmt.ShapeRange.ScaleHeight = 3.0

wb.SaveAs(os.path.join(dirpath, outputfile))
excel.Application.Quit()

I think ShapeRange.ScaleWidth, ShapeRange.ScaleHeight is the way to specify the comment box scaling but I am not getting the attributes right and getting an error. Ideally I want to auto adjust the dimensions of the comment box. Any suggestions?


Solution

  • Found two ways:

    cmt.Shape.Width = 300
    cmt.Shape.Height = 100
    

    or

    cmt.Shape.TextFrame.AutoSize = True