如何使用Python编写Excel注释?

4
我是一名Python程序员,需要在Excel电子表格中批量插入注释。有没有人知道使用Python脚本的简单/实用方法?(如果有示例,也可以是JavaScript)
它可以是.xls、.xlsx或.ods格式,并且可以在任何操作系统上使用(尽管我是Linux用户,所以如果我的解决方案可在Linux上移植,那就更好了)。
我已经尝试使用Python的xlwt模块并搜索了使用csv的某种方法来实现此目的,但没有成功。
3个回答

2
这是一段 Python 代码,使用 Windows 上的 pywin32 包启动 Excel,打开一个电子表格并在 A1 单元格中创建一个注释:
>>> import win32com.client
>>> xl = win32com.client.Dispatch("Excel.Application")
>>> xl.Visible = 1
>>> wb = xl.Workbooks.Open(r'<full path of excel spreadsheet>')
>>> sheet = wb.ActiveSheet
>>> sheet.Range("A1").AddComment()
<COMObject AddComment>
>>> sheet.Range("A1").Comment.Visible = True
>>> sheet.Range("A1").Comment.Text("Hello World")
u'Hello World'
>>> wb.SaveAs(r'<full path of modified spreadsheet>')
>>> wb.Close()
>>> xl.Quit()

我刚刚在Windows 7上使用Python 2.7.2和Excel 2007运行了这个代码,对我来说它是有效的。

1
如果您需要将大量包含公式(以及注释)的数据导出到Excel中,可以使用名为portable-spreadsheet的库(pip install portable-spreadsheet)。请查看使用案例的文档。它遵循以下逻辑:
import portable_spreadsheet as ps
sheet = ps.Spreadsheet.create_new_sheet(5, 5)
# Set values
sheet.iloc[0, 0] = 25  # Set A1
sheet.iloc[1, 0] = sheet.iloc[0, 0]  # reference to A1
# Export to Excel
sheet.to_excel('output/sample.xlsx')

它的工作方式与Pandas数据框架类似。

0
你可以使用openpyxl来完成这个任务。
from openpyxl import Workbook
from openpyxl.comments import Comment
wb = Workbook()

ws = wb.active

comment = Comment("This is a comment!", "Author")

# comment.width = 

ws['A1'].comment = comment

wb.save('CommentTest.xlsx')

wb.close()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接