我试图将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)
小智 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)
小智 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)
这提供了一种使用指定库的更干净的单行解决方案。
| 归档时间: |
|
| 查看次数: |
65693 次 |
| 最近记录: |