본문 바로가기

코딩/파이썬과 엑셀

openpyxl로 엑셀 다루기 016. get_column_letter 함수로 열에 대한 문자 얻기 (column letter)

python : openpyxl : get_column_letter()

get_column_letter 함수로 열에 대한 문자 얻기 (column letter)

엑셀 파일에서 행은 숫자로, 열은 문자로 표시된다.

 

엑셀 파일의 행과 열

함수 get_column_letter는 열의 인덱스 정보를 입력받고 해당 열에 대한 문자를 반환한다.

 

함수 get_column_letter의 사용 예는 아래와 같으며,

 

from openpyxl import Workbook
from openpyxl.utils import get_column_letter

wb = Workbook()
ws = wb.active

for col_num in range(1, 30):
    ws.cell(1, col_num, get_column_letter(col_num))

wb.save('sample.xlsx')

 

위의 코드를 실행하면, 각 열에 대한 문자가 행에 입력되어 있음을 볼 수 있다.

 

열 A ~ P까지의 문자를 얻고 셀에 쓰기

 

열 Q ~ AC까지의 문자를 얻고 셀에 쓰기

 

openpyxl 패키지에서 함수 get_column_letter는 cell 모듈 내에 정의되어 있으나,

 

openpyxl.utils.cell.get_column_letter(idx)
    """
    Convert a column index into a column letter (3 -> 'C')
    """

 

아래와 같이 openpyxl.utils 모듈은 get_column_letter 함수를 import하고 있기 때문에

코드 작성 시 from openpyxl.utils import get_column_letter로 import 문을 정의할 수 있다.

 

from .cell import (
    absolute_coordinate,
    cols_from_range,
    column_index_from_string,
    coordinate_to_tuple,
    get_column_letter,
    get_column_interval,
    quote_sheetname,
    range_boundaries,
    range_to_tuple,
    rows_from_range,
)