如何使用openpyxl通过DefinedName获取单元格内容?

2024-03-05

例如单元格的坐标为A1,设置aDefinedName name="cat" with coordinate='A1'。然后我想读取内容cell via DefinedName "cat"。但好像不支持。还有其他方法可以帮忙吗?请参阅此处的示例图片 https://i.stack.imgur.com/6zGFK.png

from openpyxl import load_workbook
wb = load_workbook(filename="test.xlsx")
ws = wb['Sheet1']
cat = ws['cat'].value

我是如何找到答案的

我不知道excel的功能。所以我将单元格 A1“命名”为cat并保存文件。我将文件解压为 rar 文件。cat被发现于xl/workbook.xml,原始内容为<definedName name="cat">工作表1!$A$1</definedName>。这是一个叫做definedName有属性name,其内容由工作表的title和细胞coordinate。所以该函数被称为defined name或相关的东西。我发现它在官方文档 http://openpyxl.readthedocs.io/en/default/defined_names.html

Answer

from openpyxl import load_workbook
wb = load_workbook(filename="test.xlsx")

# get DefinedNameList instance
defined_names_cat = wb.defined_names['cat']

# get destinations which is a generator
destinations_cat = defined_names_cat.destinations  
values = {}
for sheet_title, coordinate in destinations_cat:
    values.update({sheet_title: wb[sheet_title][coordinate].value})
my_value = values.get('Sheet1')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用openpyxl通过DefinedName获取单元格内容? 的相关文章

随机推荐