评论

警告

OpenPYXL目前只支持读写注释文本。格式信息丢失。注释维度在阅读时丢失,但可以写入。当前不支持注释,如果 read_only=True 使用。

向单元格添加注释

注释具有文本属性和作者属性,两者都必须设置

>>> from openpyxl import Workbook
>>> from openpyxl.comments import Comment
>>> wb = Workbook()
>>> ws = wb.active
>>> comment = ws["A1"].comment
>>> comment = Comment('This is the comment text', 'Comment Author')
>>> comment.text
'This is the comment text'
>>> comment.author
'Comment Author'

如果将同一注释分配给多个单元格,则OpenPYXL将自动创建副本

>>> from openpyxl import Workbook
>>> from openpyxl.comments import Comment
>>> wb=Workbook()
>>> ws=wb.active
>>> comment = Comment("Text", "Author")
>>> ws["A1"].comment = comment
>>> ws["B2"].comment = comment
>>> ws["A1"].comment is comment
True
>>> ws["B2"].comment is comment
False

加载和保存注释

加载时工作簿中的注释会自动存储在各自单元格的“注释”属性中。格式信息(如字体大小、粗体和斜体)将丢失,注释容器框的原始尺寸和位置也将丢失。

工作簿保存时保留在其中的注释将自动保存到工作簿文件中。

注释维度只能为写指定。注释尺寸以像素为单位。

>>> from openpyxl import Workbook
>>> from openpyxl.comments import Comment
>>> from openpyxl.utils import units
>>>
>>> wb=Workbook()
>>> ws=wb.active
>>>
>>> comment = Comment("Text", "Author")
>>> comment.width = 300
>>> comment.height = 50
>>>
>>> ws["A1"].comment = comment
>>>
>>> wb.save('commented_book.xlsx')

如果需要, openpyxl.utils.units 包含用于从其他度量值(如mm或点)转换为像素的辅助函数:

>>> from openpyxl import Workbook
>>> from openpyxl.comments import Comment
>>> from openpyxl.utils import units
>>>
>>> wb=Workbook()
>>> ws=wb.active
>>>
>>> comment = Comment("Text", "Author")
>>> comment.width = units.points_to_pixels(300)
>>> comment.height = units.points_to_pixels(50)
>>>
>>> ws["A1"].comment = comment