[英]Reading a named range from excel - Python - xlrd
Following is the piece of code that I wrote, and I'm unable to proceed beyond reading the range. 以下是我编写的代码,我无法继续阅读该范围。 I want to be able to read the actual content of the range.
我希望能够读取范围的实际内容。 Any help is appreciated.
任何帮助表示赞赏。
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.
the xlrd, xlwt, xlutils are meant for .xls
files per their documentation. xlrd,xlwt,xlutils根据其文档适用于
.xls
文件。 It recommends openpyxl for .xlsx
files. 对于
.xlsx
文件,建议使用openpyxl。 Then you can use this: 然后,您可以使用以下代码:
Read values from named ranges with openpyxl 使用openpyxl从命名范围读取值
My method is to find out his column coordinates, 我的方法是找出他的列坐标,
but I still recommend using openpyxl
to be more intuitive. 但我仍然建议使用
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.