python - 使用 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”......
解决方案
根据错误消息,听起来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
,然后再给它赋值,是相当荒谬的;它不会导致两个值以任何有趣的方式相关。第二个更有可能实际更改您的工作表。
推荐阅读
- db2 - 获取有关架构、表、主键的信息
- java - Spring boot 字段需要一个找不到类型的 bean
- java - Google zxing api无法解码条形码
- php - 获取最后一条推文 Twitter api
- android-testing - Android Robolectric 检查编辑文本是否显示错误消息
- ios - 响应 ios/xamarin 上的特定拨打电话号码
- javascript - 在 OctoberCMS Javascript 文件中访问 Twig 变量
- javascript - 如何从 React.js 中的 .map() 数组内部访问`this`?
- c# - 用于代码优化的 Activator.CreateInstance 替代方案
- python - 芹菜工人在 Matplotlib subplot() 期间过早退出