我想用xlwings从受保护的Excel表格中获取评论,但返回None

0 投票
1 回答
60 浏览
提问于 2025-04-14 16:00

我想用Python和xlwings从一个受保护的Excel表格中获取评论,但即使单元格里有评论,它却返回了None。

import pandas as pd
import xlwings as xw


PATH = 'C:/Users/Hendo/Pictures/Sample.xlsx'
psw = '1234'
wb = xw.Book(PATH, password= psw)
sheet = wb.sheets['Sheet1']
print(sheet.range('H15').note)
print(sheet.range('H15').value)

它打印出来的是:

None
AAAA

我希望能返回单元格的评论。

1 个回答

0

使用pywin32接口,试着把你的代码改成下面这样:

import xlwings as xw


PATH = 'C:/Users/Hendo/Pictures/Sample.xlsx'
psw = '1234'

wb = xw.Book(PATH, password=psw)
sheet = wb.sheets['Sheet1']

print(sheet.range('H15').api.Comment.Text())
print(sheet.range('H15').value)

另一种方法
这样做会打印出工作簿中所有工作表上的所有评论。

import xlwings as xw


excel_file = 'C:/Users/Hendo/Pictures/Sample.xlsx'
with xw.App(visible=False) as app:
    wb = xw.Book(excel_file)

    for sheet in wb.sheets:
        print(f"----Sheet '{sheet.name}'------------")
        for cmt in sheet.api.Comments:
            print(f"Comment Co-ordinate: {cmt.Parent.Address.replace('$', '')}")
            print(f"Comment Author: {cmt.Author}")
            print(f"Comment Text: {sheet.range(cmt.Parent.Address).api.Comment.Text()}")
            print("----------------")

撰写回答