首页 > 解决方案 > 使用 Python 2.7 向 Excel 单元格添加注释

问题描述

我正在使用 Python 2.7,我尝试做这里的事情(使用 Python 向 excel 文件工作表添加注释),但这不起作用......

这是我的代码:

import os, sys, shutil, time, openpyxl
from openpyxl import Workbook
from openpyxl.comments import Comment
...
path = 'K:/....../data.xlsx'
wb = Workbook()
ws = wb.active
...
comment = ws["A1"].comment
comment = Comment('This is the comment text', 'Comment Author')
...
wb.save(path)

我也试过:

comment = Comment('This is the comment text', 'Comment Author')
ws["A1"].comment = comment

但这是否会创建我的 xlsx 文件而不对“A1”单元格进行注释,这是否告诉我“TypeError:预期类型 'unicode'”和“引发 TypeError('expected ' + str(expected_type))”。

你能帮我解决这个问题吗?谢谢

注意:我也试过这个,但它说“没有属性 AddComment”......

标签: pythonexcelpython-2.7openpyxl

解决方案


根据错误消息,听起来Comment它的参数是 Unicode,但你给它的是 8 位字符串。尝试给它 Unicode 字符串。

comment = Comment(u'This is the comment text', u'Comment Author')

如果您在想“但是为什么我需要在文档u中的示例中不这样做时为我的文字添加前缀?”,那么这些示例很可能使用的是 Python 3,其中未加前缀的字符串文字被解释为统一码。


至于“这些哪个是正确的?”的问题:

comment = ws["A1"].comment
comment = Comment(u'This is the comment text', u'Comment Author')

或者

comment = Comment(u'This is the comment text', u'Comment Author')
ws["A1"].comment = comment

第二个对我来说更有意义。给变量赋值comment,然后再给它赋值,是相当荒谬的;它不会导致两个值以任何有趣的方式相关。第二个更有可能实际更改您的工作表。


推荐阅读