I can set and delete comments in an Excel sheet but am unable to get (read)the contents of an existing comment. xlwings doesn't have a method for it so you need to drop down to the com object.
import xlwings as xw
wb = xw.Workbook.active()
xw.Range('A1').api.AddComment('Some Text')
xw.Range('A1').api.DeleteComment()
xw.Range('A1').api.AddComment('More Text')
# Sadness on my best effort so far
comment_text = xw.Range('A1').api.Comment.Shape.TextFrame.Characters.Text
The code in the OP nor the suggested answer works for me. Here is how I did it in xlwings version 0.11.5 (on windows if that matters, Excel 2013, 2016, 2019):
Adding comments to a cell (Please note you have to clear the comment if a comment already exists!):
import xlwings as xw
path_to_excel_file = r'c:\temp\test.xlsx'
wb = xw.Book(path_to_excel_file)
sheet = wb.sheet['Sheet1']
coordinate = (1,1)
comment = "test comment"
sheet.range(coordinate).api.ClearComments()
sheet.range(coordinate).api.AddComment(comment)
Reading the value of a comment:
import xlwings as xw
path_to_excel_file = r'c:\temp\test.xlsx'
wb = xw.Book(path_to_excel_file)
sheet = wb.sheet['Sheet1']
coordinate = (1,1)
xlsx_comment = sheet.range(coordinate).api.comment
if xlsx_comment is not None:
print(xlsx_comment.text())
else:
print("No comment in this cell.")
I always have to google how to do it and I come across this thread so I figured this should be documented somewhere. Happy hunting!