我使用的是Python 2.7,我尝试做here(用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'”和“ raise TypeError('expected'+ str(expected_type))”。
您能帮我解决这个问题吗?谢谢
:我也尝试过this,但是它说“没有属性AddComment” ...
答案 0 :(得分:3)
按照错误消息进行操作,听起来Comment
期望它的参数为Unicode,但是您要为其提供8位字符串。尝试改用Unicode字符串。
comment = Comment(u'This is the comment text', u'Comment Author')
如果您正在考虑“但是在documentation的示例中,为什么我的文字未使用u
作为前缀?”,那么这些示例很可能是使用Python 3,其中未加前缀的字符串文字被解释为Unicode。
至于“哪个是正确的?”的问题:
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
分配一个值,然后给它分配第二个值是很荒谬的。不会导致这两个值以任何有趣的方式关联。第二个更有可能实际更改您的工作表。
答案 1 :(得分:0)
#full script on xlsxwriter
import xlsxwriter
workbook = xlsxwriter.Workbook('chart_styles.xlsx')
# Show the styles for all of these chart types.
chart_types = ['column', 'area', 'line', 'pie']
for chart_type in chart_types:
# Add a worksheet for each chart type.
worksheet = workbook.add_worksheet(chart_type.title())
worksheet.set_zoom(30)
style_number = 1
# Create 48 charts, each with a different style.
for row_num in range(0, 90, 15):
for col_num in range(0, 64, 8):
chart = workbook.add_chart({'type': chart_type})
chart.add_series({'values': '=Data!$A$1:$A$6'})
chart.set_title ({'name': 'Style %d' % style_number})
chart.set_legend({'none': True})
chart.set_style(style_number)
worksheet.insert_chart(row_num, col_num , chart)
style_number += 1
# Create a worksheet with data for the charts.
data_worksheet = workbook.add_worksheet('Data')
data = [10, 40, 50, 20, 10, 50]
data_worksheet.write_column('A1', data)
data_worksheet.hide()
workbook.close()