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
반응형
'파이썬' 카테고리의 다른 글
파이썬과 MySQL연동하는 방법 (0) | 2023.10.23 |
---|---|
파이썬으로 엑셀로 저장할 때 수식을 넣어서 연동 (0) | 2023.07.28 |
파이썬에서 명령문 병렬로 처리하기 (0) | 2023.06.18 |
PDF문서에 표 데이터를 수집하는 방법. (0) | 2023.06.16 |
ChatGPT로 이미지 생성하는 2가지 Two ways to generate images with ChatGPT (0) | 2023.04.17 |