Python xlrd命名范围值

Dic*_*ter 3 python excel xlrd named-ranges

在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??
Run Code Online (Sandbox Code Playgroud)

我只想在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()
Run Code Online (Sandbox Code Playgroud)

这里有Formula_text以确保excel可以读取文件。在我的情况下,在Sheet1的单元格A1中,命名的单元格为“ sales”。

返回值:

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'
Run Code Online (Sandbox Code Playgroud)

jon*_*one 5

首先,它是小写字母,如xlrd模块信息(https://secure.simplistix.co.uk/svn/xlrd/trunk/xlrd/doc/xlrd.html?p=4966)中所述:

name_map [#]

从lower_case_name到Name对象列表的映射。该列表按范围顺序排序。通常,列表中只有一项(全局范围)。

您有两个选择。如果您确实只为单个单元格设置了名称,则可以使用Name类的“ cell”方法(请参阅文档):

import xlrd
book = xlrd.open_workbook("")
Name = book.name_map['foo'][0]
print(Name.cell())
Run Code Online (Sandbox Code Playgroud)

安慰:

text:'Bar'
Run Code Online (Sandbox Code Playgroud)

但是,如果已命名整个值范围,则需要使用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))
Run Code Online (Sandbox Code Playgroud)

安慰:

text:'Bar'
Run Code Online (Sandbox Code Playgroud)

  • 正如我上面提到的 cell() 给了我一个错误:AttributeError: 'NoneType' object has no attribute 'logfile' (Sheet.cell(i,0)) 也给了我同样的错误) (2认同)