请注意,Openpyxl目前仅支持读写批注文本,文本格式化信息将丢失。批注尺寸在读取时丢失,但可以写入。如果使用read_only=True
,则当前不支持批注。
向单元格添加批注¶
批注有一个文本属性和一个author属性,必须同时设置
>>> 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
加载和保存批注¶
加载时工作簿中出现的批注将自动存储在各自单元格的comment
属性中。格式信息(如字体大小、粗体和斜体)将丢失,批注容器框的原始尺寸和位置也将丢失。
工作簿保存时保留在其中的批注将自动保存到工作簿文件中。
只能为写入指定批注尺寸。批注尺寸以像素为单位。
>>> 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