从openpyxl中的坐标值获取行号和列号

A A*_*one 33 python openpyxl

我试图将excel中的坐标值转换为openpyxl中的行号和列号.

例如,如果我的单元坐标是D4,我想找到用于将来操作的相应行号和列号,在行= 3,列= 3的情况下.我可以轻松地使用ws.cell('D4').row哪个返回行号 ,4那么这只是一个问题减去1.但是类似的参数ws.cell('D4').column返回D,我不知道如何轻松地将其转换为int形式以用于后续操作.所以我向你转向stackoverflow的聪明人.你能帮助我吗?

Ada*_*ris 51

你想要的是openpyxl.utils.coordinate_from_string()openpyxl.utils.column_index_from_string()

from openpyxl.utils.cell import coordinate_from_string, column_index_from_string
xy = coordinate_from_string('A4') # returns ('A',4)
col = column_index_from_string(xy[0]) # returns 1
row = xy[1]
Run Code Online (Sandbox Code Playgroud)

  • 对于使用最新版本的openpyxl(版本2.3.1大约2015年11月20日)的任何人,请记住,某些功能定义已移至包的不同部分.现在必须"从openpyxl.utils"导入"coordinate_from_string"和"column_index_from_string".请参阅文档[此处](http://openpyxl.readthedocs.org/en/default/api/openpyxl.utils.html) (7认同)
  • 文档不多 - 它是由phpexcel构建的 - http://phpexcel.codeplex.com,并且存在重大差异.对于python项目,代码结构很好 - 有很多你可以找到只是查看源代码中的单元测试. (2认同)
  • 不确定何时开始,但至少从``openpyxl-utilities == 0.5''开始(截至2019年),您将使用``从openpyxl.utils.cell import axis_from_string,column_index_from_string''进行导入 (2认同)

小智 42

openpyxl有一个名为get_column_letter的函数,它将数字转换为列字母.

from openpyxl.utils import get_column_letter
print(get_column_letter(1))
Run Code Online (Sandbox Code Playgroud)

1 - > A.

50 - > AX

1234-- AUL

我一直在使用它:

from openpyxl import Workbook
from openpyxl.utils import get_column_letter

#create excel type item
wb = Workbook()
# select the active worksheet
ws = wb.active

counter = 0
for column in range(1,6):
    column_letter = get_column_letter(column)
    for row in range(1,11):
        counter = counter +1
        ws[column_letter + str(row)] = counter

wb.save("sample.xlsx")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • OP希望将列字母转换为索引号,但反过来更困难,更不明显.处理这个问题的好方法很好,干净. (2认同)

小智 7

openpyxl.utils.cell模块中有一个方法可以满足所需的功能。该方法openpyxl.utils.cell.coordinate_to_tuple()将字母数字 Excel 坐标作为字符串作为输入,并将这些坐标作为整数元组返回。

openpyxl.utils.cell.coordinate_to_tuple('B1')
>> (1, 2)
Run Code Online (Sandbox Code Playgroud)

这提供了一种使用指定库的更干净的单行解决方案。