OpenPyXL 坐标到元组方法在绝对地址上失败

问题描述 投票:0回答:1

相当简单的OpenPyXL问题...如何更改以下行以返回绝对地址单元格的地址元组?我可以手动删除美元符号,但对于 OpenPyXL 中的错误来说,这似乎是一个肮脏的解决方法。

# The following line results in the error:
# Traceback (most recent call last):
#   ...
#     coordinates = coordinate_to_tuple('$A$2')
#   File "/usr/local/lib/python3.8/dist-packages/openpyxl/utils/cell.py", line 202, in coordinate_to_tuple
#     return int(row), _COL_STRING_CACHE[col]
# KeyError: '$A$'
coordinates = coordinate_to_tuple('$A$2')

# The following are all hacky work-arounds to return a tuple (row, col)
# Working hack 1
coords = coordinate_to_tuple('$A$2'.replace('$', ''))
# Working hack 2
coords = range_boundaries('$A$2')[1:3]
# Working hack 3
coords = coordinate_from_string('$A$2')
coords = (coords[1], column_index_from_string(coords[0]))

也许有一种方法可以撤消对

absolute_coordinate
的调用,而我在 OpenPyXL utils 文档中缺少该方法?或者是在作为公共 API 一部分的某个常量中定义的文字美元符号?除非有人提出更好的方法,否则我将继续使用 hack#1。

python openpyxl
1个回答
0
投票

coordinate_to_tuple()
是一个优化函数,用于在读取可能包含数百万个单元格的工作表时处理单元格地址;而
coordinate_from_string()
更通用,适合这种风格更常见的函数和范围。在这种情况下,添加另一行来获得你想要的东西是完全可以的(减少行数不是 Python 的目标),而不是 hack。

看看代码库中实际使用的内容,看起来像

range_…
函数用于您可以期望这些类型的地址的地方,但
range_boundaries(coord)[:2]
可能是您想要的,并且可以让您轻松处理单个单元格和范围。

© www.soinside.com 2019 - 2024. All rights reserved.