본문 바로가기

파이썬

파이썬으로 엑셀 행 높이 자동조절하는 코드

728x90
반응형

파이썬으로 엑셀 행 높이 자동조절하는 코드

from openpyxl import Workbook

def autofit_row_height(worksheet):
    for row in worksheet.iter_rows():
        for cell in row:
            if cell.value:
                # 1. Calculate the number of lines needed for the cell content
                lines = cell.value.count('\n') + 1

                # 2. Calculate the required height for the cell based on the default font size
                font_size = 11  # Change this value as needed
                cell_height = (font_size * 1.3) * lines

                # 3. Set the row height to fit the cell content
                if worksheet.row_dimensions[cell.row].height is None or worksheet.row_dimensions[cell.row].height < cell_height:
                    worksheet.row_dimensions[cell.row].height = cell_height

# 예시를 위해 새로운 워크북을 만듭니다.
workbook = Workbook()
worksheet = workbook.active

# 데이터 입력
worksheet['A1'] = "첫 번째 셀에 여러 줄의 내용을 입력합니다.\n두 번째 줄입니다.\n세 번째 줄입니다."

# 열 너비와 행 높이를 자동으로 조절합니다.
for column_cells in worksheet.columns:
    for cell in column_cells:
        if cell.value:
            # 4. Calculate the required width for the column based on the content length
            column_width = (len(str(cell.value)) * 1.2)

            # 5. Set the column width to fit the cell content
            if worksheet.column_dimensions[cell.column_letter].width is None or worksheet.column_dimensions[cell.column_letter].width < column_width:
                worksheet.column_dimensions[cell.column_letter].width = column_width

# 행 높이를 자동으로 조절합니다.
autofit_row_height(worksheet)

# 파일을 저장합니다.
workbook.save("example.xlsx")

파이썬으로 엑셀 행 높이 자동조절하는 코드

728x90
반응형