【问题标题】:How I can add a specific comment in excel with pandas?如何在带有熊猫的 excel 中添加特定评论?
【发布时间】:2021-12-21 11:58:39
【问题描述】:
这是数据框:
我想在endingBalanceLC 列的黄色单元格中添加评论。问题是我不知道这个帐户和 aferent 总数在我的数据框中的确切位置,因为位置总是可以改变,这取决于 excel。我要添加的评论是“这是余额”。
我正在考虑使用xlsxwriter,但我不知道如何。
【问题讨论】:
标签:
python
excel
pandas
openpyxl
xlsxwriter
【解决方案1】:
这是一个示例,说明如何使用openpyxl 读取文件、检测具有特定背景颜色的单元格,以及向这些单元格添加注释。
import openpyxl
from openpyxl import load_workbook
from openpyxl.comments import Comment
excel_file = 'sample.xlsx'
wb = load_workbook(excel_file, data_only = True)
sh = wb['Sheet1']
# iterate through excel and display data
for i in range(1, sh.max_row+1):
for j in range(1, sh.max_column+1):
## check if the background is yellow
if sh.cell(row=i, column=j).fill.start_color.index == 'FFFFFF00':
sh.cell(row=i, column=j).comment = Comment("This is a balance account", "author name")
wb.save('commented_sample.xlsx')
您可以覆盖原始文件,或者创建一个新的 xlsx 文件,如下所示: