[excel - python - uipath] 엑셀 자동화에 대해서 알아보자(3-2)

루까까·2023년 8월 1일
0

Excel 자동화

목록 보기
6/25

이번 시간에는 Autofit Range activity를 python 코드로 구현해보는 시간을 가져보자.
(uipath Autofit Range activity 알아보기)

1. 전체 코드

def autofit_range(file_name, sheet_name: [str,int], column_y_n: bool = True, row_y_n: bool = True):

    wb = load_workbook(file_name)
    ws = wb[sheet_name]

    if column_y_n:
        for column_cells in ws.columns:
            max_length = 0
            for cell in column_cells:
                try:
                    if len(str(cell.value)) > max_length:
                        max_length = len(cell.value)
                except:
                    pass
            adjusted_width = (max_length + 2) * 1.2
            ws.column_dimensions[column_cells[0].column_letter].width = adjusted_width

    if row_y_n:
        for row_cells in ws.rows:
            max_height = 0
            for cell in row_cells:
                try:
                    lines = str(cell.value).count("\n") + 1
                    height = (lines * 12) + 4
                    if height > max_height:
                        max_height = height
                except:
                    pass
            ws.row_dimensions[row_cells[0].row].height = max_height

    wb.save(file_name)

2. 코드 설명

2-1. 함수 인자 정의

def autofit_range(file_name, sheet_name: [str,int], column_y_n: bool = True, row_y_n: bool = True):
  • file_name은 엑셀명 기입
  • sheet_name은 엑셀 시트명 기입(위치도 입력 가능)
  • column_y_n은 열 자동 맞춤 여부(기본값은 True)
    • uipath Autofit Range activity의 열 체크박스와 동일 기능
  • row_y_n은 행 자동 맟춤 여부(기본값은 True)
    • uipath Autofit Range activity의 행 체크박스와 동일 기능

2-2. 자동 열 맞춤

for column_cells in ws.columns:
    max_length = 0
    for cell in column_cells:
        try:
            if len(str(cell.value)) > max_length:
                max_length = len(cell.value)
        except:
            pass
    adjusted_width = (max_length + 2) * 1.2
    ws.column_dimensions[column_cells[0].column_letter].width = adjusted_width
  • 시트의 모든 열값을 기준으로 진행
  • 열이 없을 경우 pass
  • 기본적으로 열 너비는 (최대 열 너비의 + 2) * 1.2 다.
    • 숫자의 경우 본인이 원하는 대로 수정해서 사용 가능
    • 필자는 1.2배가 보기 좋아서 해당 숫자로 기입

2-3. 자동 행 맞춤

for row_cells in ws.rows:
    max_height = 0
    for cell in row_cells:
        try:
            lines = str(cell.value).count("\n") + 1
            height = (lines * 12) + 4
            if height > max_height:
                max_height = height
        except:
            pass
    ws.row_dimensions[row_cells[0].row].height = max_height
  • 시트의 모든 행값을 기준으로 진행
  • 행이 없을 경우 pass
  • cell의 줄바꿈을 계산해서 시트의 최대 행 높이를 계산
  • 최대 행 높이에 여유 높이 4를 추가적으로 기입
    • 숫자의 경우 본인이 원하는 대로 수정해서 사용 가능
    • 필자는 +4가 보기 좋아서 해당 숫자로 기입
    • 12의 경우 기본 글자 크기를 의미(기본적으로 12포인트임으로 12로 기입)

모든 각 행과 각 열을 조회하여 가장 큰 너비와 높이를 구하여
해당 값을 바탕으로 자동 맞춤을 진행하는 코드이기에
데이터가 많아지면 그만큼 시간이 많이 소비되는 단점을 가지고 있다.

profile
기타치는 개발자

0개의 댓글