定义的名字¶
该规范对已定义的名称做了如下说明:
“定义名称是用来表示单元格、单元格范围、公式或常量值的描述性文本。”
这意味着它们的定义非常宽泛。它们可能包含常数、公式、单个单元格引用、单元格范围或跨不同工作表的多个单元格范围。或者以上都有。它们是为工作簿全局定义的,可以通过 defined_names
属性访问。”
范围的样本使用¶
访问范围的名为 “my_range”:
my_range = wb.defined_names['my_range']
# if this contains a range of cells then the destinations attribute is not None
dests = my_range.destinations # returns a generator of (worksheet title, cell range) tuples
cells = []
for title, coord in dests:
ws = wb[title]
cells.append(ws[coord])
创建新的命名范围¶
import openpyxl
wb = openpyxl.Workbook()
new_range = openpyxl.workbook.defined_name.DefinedName('newrange', attr_text='Sheet!$A$1:$A$5')
wb.defined_names.append(new_range)
# create a local named range (only valid for a specific sheet)
sheetid = wb.sheetnames.index('Sheet')
private_range = openpyxl.workbook.defined_name.DefinedName('privaterange', attr_text='Sheet!$A$6', localSheetId=sheetid)
wb.defined_names.append(private_range)
# this local range can't be retrieved from the global defined names
assert('privaterange' not in wb.defined_names)
# the scope has to be supplied to retrieve local ranges:
print(wb.defined_names.localnames(sheetid))
print(wb.defined_names.get('privaterange', sheetid).attr_text)
['privaterange']
Sheet!$A$6