+-
Python xlrd命名范围值
在 Python中使用XLRD从Excel中读取.

简单的场景.我有一个带有值的单元格,这与命名范围相关联.

NamedRange“Foo”= Sheet1!$A $1
A1中的值是“Bar”

book =xlrd.open_workbook("")

rng =  book.name_map['foo'][0]  # lower case for some reason.

print rng.???   # how to print the cell value bar??

我只想在python代码中引用命名范围“Foo”并打印出单元格的值“Bar”.

编辑:
这是另一个更完整的例子:

import xlrd

workbook = xlrd.open_workbook('/path/to/metester.xls')
cell_obj = workbook.name_and_scope_map.get(('sales', -1))
# this does print Sheet1!$A$1
print cell_obj.formula_text
# this raises the NoneTypeError
print cell_obj.cell()

formula_text是为了确保excel可以读取文件.在我的例子中,命名单元格是Sheet1中的“sales”,单元格A1.

返回:

Sheet1!$A$1
Traceback (most recent call last):
  File "tester.py", line 7, in <module>
    print cell_obj.cell()
  File "/usr/local/lib/python2.7/dist-packages/xlrd/book.py", line 253, in cell
    self.dump(self.book.logfile,
AttributeError: 'NoneType' object has no attribute 'logfile'
最佳答案
首先,它是小写,如xlrd模块信息( https://secure.simplistix.co.uk/svn/xlrd/trunk/xlrd/doc/xlrd.html?p=4966)中所述:

name_map [#]

A mapping from lower_case_name to a list of Name objects. The list is sorted in scope order. Typically there will be one item (of global scope) in the list.

你有两个选择.如果你真的只设置一个单元格的名称,那么你使用Name类的’cell’方法(参见文档):

import xlrd
book = xlrd.open_workbook("")
Name = book.name_map['foo'][0]
print(Name.cell())

安慰:

text:'Bar'

但是,如果您已命名整个值范围,则需要使用Name类的area2d方法:

import xlrd
book = xlrd.open_workbook("q1.xls")
Name = book.name_map['foo'][0]
Sheet, rowxlo, rowxhi, colxlo, colxhi = Name.area2d()
for i in range(rowxhi):
    print(Sheet.cell(i,0))

安慰:

text:'Bar'
点击查看更多相关文章

转载注明原文:Python xlrd命名范围值 - 乐贴网