Получение номеров строк и столбцов от значения координаты в openpyxl
Я пытаюсь скрыть значение координаты в excel до номера строки и номера столбца в openpyxl.
Например, если моя координата ячейки D4, я хочу найти соответствующие номера строк и столбцов, которые будут использоваться для будущих операций, в случае row = 3, column = 3. Я могу легко получить номер строки, используя ws.cell('D4').row
, который возвращает 4
, тогда это просто вопрос вычитания 1. Но аналогичный аргумент ws.cell('D4').column
возвращает D
, и я не знаю, как легко получить его в форме int для последующих операций. Поэтому я обращаюсь к вам мудрым людям из stackoverflow. Можете ли вы мне помочь?
Ответы
Ответ 1
Вы хотите openpyxl.utils.coordinate_from_string()
и openpyxl.utils.column_index_from_string()
from openpyxl.utils 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]
Ответ 2
openpyxl имеет функцию с именем get_column_letter, которая преобразует число в букву столбца.
from openpyxl.utils import get_column_letter
print(get_column_letter(1))
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")
![введите описание изображения здесь]()
Ответ 3
Это построение ответа Натана. В принципе, его ответ не работает должным образом, когда строка и/или столбец имеют ширину более одного символа. Извини, я пошел немного над доской. Вот полный script:
def main():
from sys import argv, stderr
cells = None
if len(argv) == 1:
cells = ['Ab102', 'C10', 'AFHE3920']
else:
cells = argv[1:]
from re import match as rematch
for cell in cells:
cell = cell.lower()
# generate matched object via regex (groups grouped by parentheses)
m = rematch('([a-z]+)([0-9]+)', cell)
if m is None:
from sys import stderr
print('Invalid cell: {}'.format(cell), file=stderr)
else:
row = 0
for ch in m.group(1):
# ord('a') == 97, so ord(ch) - 96 == 1
row += ord(ch) - 96
col = int(m.group(2))
print('Cell: [{},{}] '.format(row, col))
if __name__ == '__main__':
main()
Tl; dr с кучей комментариев...
# make cells with multiple characters in length for row/column
# feel free to change these values
cells = ['Ab102', 'C10', 'AFHE3920']
# import regex
from re import match as rematch
# run through all the cells we made
for cell in cells:
# make sure the cells are lower-case ... just easier
cell = cell.lower()
# generate matched object via regex (groups grouped by parentheses)
############################################################################
# [a-z] matches a character that is a lower-case letter
# [0-9] matches a character that is a number
# The + means there must be at least one and repeats for the character it matches
# the parentheses group the objects (useful with .group())
m = rematch('([a-z]+)([0-9]+)', cell)
# if m is None, then there was no match
if m is None:
# let tell the user that there was no match because it was an invalid cell
from sys import stderr
print('Invalid cell: {}'.format(cell), file=stderr)
else:
# we have a valid cell!
# let grab the row and column from it
row = 0
# run through all of the characters in m.group(1) (the letter part)
for ch in m.group(1):
# ord('a') == 97, so ord(ch) - 96 == 1
row += ord(ch) - 96
col = int(m.group(2))
# phew! that was a lot of work for one cell ;)
print('Cell: [{},{}] '.format(row, col))
print('I hope that helps :) ... of course, you could have just used Adam\ answer,\
but that isn\'t as fun, now is it? ;)')
Ответ 4
Вы можете просто использовать чистый Python:
cell = "D4"
col = ord(cell[0]) - 65
row = int(cell[1:]) - 1
Здесь используется функция ord
, которая берет символ и возвращает код ASCII. В ASCII буква A
равна 65, B
равно 66 и т.д.