Чтение именованного диапазона из excel - Python - xlrd - PullRequest
0 голосов
/ 21 марта 2019

Ниже приведен фрагмент кода, который я написал, и я не могу выйти за пределы диапазона.Я хочу быть в состоянии прочитать фактическое содержание диапазона.Любая помощь приветствуется.

import xlrd
xlBook = xlrd.open_workbook('data.xlsx')
# Open the sheet
sht = xlBook.sheet_by_name('calc')
# Look at the named range
named_obj = xlBook.name_map['load'][0]

# Now, able to retrieve the range
rangeData = (named_obj.formula_text)
(sheetName,ref) = rangeData.split('!')
# Gives me the range as $A$2:$B$20
print(ref)
# How do I print the contents of the cells knowing the range.

Ответы [ 2 ]

1 голос
/ 21 марта 2019

Мой метод состоит в том, чтобы узнать координаты его столбца,

, но я все же рекомендую использовать openpyxl для большей интуитивности.

def col2int(s: str):
    weight = 1
    n = 0
    list_s = list(s)
    while list_s:
        n += (ord(list_s.pop()) - ord('A')+1) * weight
        weight *= 26
    return n

# ...
# How do I print the contents of the cells knowing the range. ↓
temp, col_start, row_start, col_end, row_end = ref.replace(':', '').split('$')
for row in range(int(row_start)-1, int(row_end)):
    for col in range(col2int(col_start)-1, col2int(col_end)):
        print(sht.cell(row, col).value)

enter image description here

1 голос
/ 21 марта 2019

xlrd, xlwt, xlutils предназначены для .xls файлов согласно их документации.Он рекомендует openpyxl для .xlsx файлов.Затем вы можете использовать это:
Чтение значений из именованных диапазонов с помощью openpyxl

...