使用 pywin32 (XLWINGS) 你如何阅读现有评论的文本?

Using pywin32 (XLWINGS) how do you read the text of an existing comment?

我可以在 Excel sheet 中设置和删除评论,但无法获取(读取)现有评论的内容。 xlwings 没有它的方法,所以你需要下拉到 com 对象。

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

Question: ... how do you read the text of an existing comment?
My problem is reading the comment not writing it

不要打扰链接标题 How to write excel comments using python? ,答案也显示 正在阅读。使用的示例令人困惑,因为它将传递的 Comment 显示为 returned String:

>>> sheet.Range("A1").Comment.Text("Hello World")
u'Hello World'

Comment.Text method

returnValue = instance.Text(Text, Start, Overwrite)

Parameters
Text Type: System.Object Optional Object. The text to be added.
Start Type: System.Object Optional Object. The character number where the added text will be placed. If this argument is omitted, any existing text in the comment is deleted.
Overwrite Type: System.Object Optional Object. True to overwrite the existing text. The default value is False (text is inserted).
Return value
Type: System.String

As all 参数 Optional, Text() return Comment Text。

>>> sheet.Range("A1").Comment.Text()
u'Hello World'

OP 中的代码和建议的答案都适合我。这是我在 xlwings 版本 0.11.5 中的做法(如果重要,windows,Excel 2013、2016、2019):

向单元格添加评论(请注意,如果评论已存在,您必须清除评论!):

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)

正在读取评论的值:

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.")

我总是需要 google 如何去做,我遇到了这个线程,所以我认为这应该记录在某个地方。狩猎愉快!