Python和Excel通过其名称而不是其坐标来获取单元格值

时间:2017-02-28 18:07:51

标签: python excel pandas

如何通过访问在Excel中创建的单元格名称来获取Python 2.7的单元格值,而不是提供坐标?

在这种情况下,访问" Surname"而不是D8:

IMG:http://www.hosting.universalsite.org/image-excel-EBA2_58B5BC06.png

1 个答案:

答案 0 :(得分:1)

openpyxl支持defined names

docs中的示例:

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])

假设'Surname'仅适用于一个单元格,您可以按如下方式提取它:

from openpyxl import load_workbook
wb = load_workbook(filename='your_workbook.xlsx')
title, coord = next(wb.defined_names['Surname'].destinations)
result = wb[title][coord].value