이번 시간에는 Autofit Range activity를 python 코드로 구현해보는 시간을 가져보자.
(uipath Autofit Range activity 알아보기)
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)
def autofit_range(file_name, sheet_name: [str,int], column_y_n: bool = True, row_y_n: bool = True):
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
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
모든 각 행과 각 열을 조회하여 가장 큰 너비와 높이를 구하여
해당 값을 바탕으로 자동 맞춤을 진행하는 코드이기에
데이터가 많아지면 그만큼 시간이 많이 소비되는 단점을 가지고 있다.