Python openpyxl 셀 서식 지정하기 - 글꼴, 색, 테두리, 열 너비, 조건부 서식
openpyxl 설치 및 사용법과 간단한 사용방법에서는 엑셀 파일을 만들고 값을 읽고 쓰는 방법을 다뤘다. 이번 글은 그다음 단계다. 파이썬으로 만든 엑셀 파일을 사람이 보기 좋게 꾸미는 방법, 곧 글꼴, 배경색, 정렬, 테두리, 숫자 형식, 열 너비, 틀 고정, 조건부 서식을 차례로 살펴본다.
이 글의 코드는 openpyxl 3.1.5에서 실행해 확인했고, 코드 아래의 결과는 실제 출력이다.
예제 데이터 만들기
지점별 석 달 매출이 담긴 작은 표를 만든다. 아직 아무 서식도 없는 상태다.
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws.title = "매출"
rows = [
["지점", "1월", "2월", "3월"],
["강남", 1250000, 1380000, 990000],
["홍대", 870000, 910000, 1120000],
["잠실", 1430000, 1205000, 1510000],
["판교", 640000, 720000, 580000],
]
for row in rows:
ws.append(row)
print(ws.dimensions, ws.max_row, ws.max_column)
A1:D5 5 4
글꼴, 배경색, 정렬
서식에 쓰는 클래스는 모두 openpyxl.styles에 있다. 머리글 행(1행)을 굵은 흰 글씨, 남색 배경, 가운데 정렬로 바꿔 보자.
from openpyxl.styles import Font, PatternFill, Alignment
for cell in ws[1]:
cell.font = Font(name="맑은 고딕", size=11, bold=True, color="FFFFFF")
cell.fill = PatternFill(fill_type="solid", start_color="1F4E78")
cell.alignment = Alignment(horizontal="center", vertical="center")
알아 둘 점이 세 가지 있다.
- 색은
"1F4E78"처럼#을 뺀 16진수 6자리로 쓴다. PatternFill은fill_type="solid"를 꼭 넣어야 한다. 빼면 색을 지정해도 칠해지지 않는다.Alignment(wrap_text=True)를 주면 셀 안에서 줄을 바꿔 준다.
이미 있는 서식을 조금만 바꾸고 싶을 때
셀에 붙은 서식 객체는 직접 고칠 수 없다. 아래처럼 쓰면 오류가 난다.
try:
ws["A2"].font.bold = True
except AttributeError as e:
print(e)
Style objects are immutable and cannot be changed.Reassign the style with a copy
오류 문구가 알려 주는 대로 복사본을 만들어 고친 다음 다시 넣으면 된다.
from copy import copy
font = copy(ws["A2"].font)
font.bold = True
ws["A2"].font = font
print(ws["A2"].font.bold)
True
테두리
테두리는 선 하나를 뜻하는 Side를 만들고, 그것을 Border의 네 방향에 넣는다. 표 전체에 얇은 회색 선을 둘러 보자.
from openpyxl.styles import Border, Side
thin = Side(style="thin", color="BFBFBF")
box = Border(left=thin, right=thin, top=thin, bottom=thin)
for row in ws.iter_rows(min_row=1, max_row=ws.max_row, max_col=ws.max_column):
for cell in row:
cell.border = box
style에는 thin, medium, thick, double, dashed, dotted 등을 쓸 수 있다.
숫자 형식 (천 단위 쉼표, 퍼센트, 날짜)
숫자에 쉼표를 넣겠다고 값을 문자열로 바꾸면 엑셀에서 합계를 낼 수 없다. 값은 숫자 그대로 두고 보이는 방식만 number_format으로 바꾼다.
for row in ws.iter_rows(min_row=2, min_col=2, max_col=4):
for cell in row:
cell.number_format = "#,##0"
print(ws["B2"].value, ws["B2"].number_format)
1250000 #,##0
값은 여전히 숫자 1250000이고, 엑셀에서는 1,250,000으로 보인다. 자주 쓰는 형식은 다음과 같다.
| 형식 문자열 | 값 | 엑셀에 보이는 모습 |
|---|---|---|
#,##0 |
1234567.891 | 1,234,568 |
#,##0.00 |
1234567.891 | 1,234,567.89 |
0.0% |
0.1234 | 12.3% |
yyyy-mm-dd |
date(2026, 9, 15) | 2026-09-15 |
#,##0"원" |
1250000 | 1,250,000원 |
열 너비와 행 높이
열 너비는 column_dimensions, 행 높이는 row_dimensions로 정한다. 너비의 단위는 대략 글자 수이고, 높이의 단위는 포인트다.
from openpyxl.utils import get_column_letter
ws.column_dimensions["A"].width = 10
for col in range(2, 5):
ws.column_dimensions[get_column_letter(col)].width = 14
ws.row_dimensions[1].height = 24
내용에 맞춰 열 너비 정하기
openpyxl에는 엑셀의 “열 너비 자동 맞춤”에 해당하는 기능이 없다. 대신 열마다 가장 긴 값의 길이를 재서 넣으면 된다. 한글은 영문보다 넓으므로 한 글자를 2칸으로 센다.
def text_width(value):
return sum(2 if ord(ch) > 127 else 1 for ch in str(value))
for cells in ws.columns:
longest = max(text_width(c.value) for c in cells if c.value is not None)
print(cells[0].column_letter, longest)
A 4
B 7
C 7
D 7
여기서 나온 길이에 여유로 2~4를 더해 width에 넣으면 된다. 쉼표가 붙는 숫자 열은 쉼표 개수만큼 더 넉넉하게 잡는다.
틀 고정과 필터
행이 많은 표는 머리글을 고정하고 필터 단추를 달아 두면 쓰기 편하다.
ws.freeze_panes = "B2"
ws.auto_filter.ref = ws.dimensions
freeze_panes에는 “이 셀의 위쪽과 왼쪽을 고정한다”는 뜻으로 셀 주소를 넣는다. "B2"면 1행과 A열이 고정되고, 머리글 행만 고정하려면 "A2"를 넣는다.
조건부 서식
조건부 서식은 값에 따라 엑셀이 알아서 색을 칠하게 하는 규칙이다. 규칙 클래스는 openpyxl.formatting.rule에 있다.
값이 기준보다 작으면 강조하기
매출이 70만 원에 못 미치는 칸을 빨간 굵은 글씨와 옅은 붉은 배경으로 표시한다.
from openpyxl.formatting.rule import CellIsRule
red_text = Font(color="C00000", bold=True)
red_fill = PatternFill(fill_type="solid", start_color="FDE9E7", end_color="FDE9E7")
ws.conditional_formatting.add(
"B2:D5",
CellIsRule(operator="lessThan", formula=["700000"], font=red_text, fill=red_fill),
)
operator에는 lessThan, greaterThan, equal, between 등을 쓴다. between은 formula=["500000", "700000"]처럼 값 두 개를 준다.
색조와 데이터 막대
숫자의 크기를 색의 진하기나 막대 길이로 보여 줄 수도 있다. 비교를 위해 시트를 따로 만들어 넣어 보자.
from openpyxl.formatting.rule import ColorScaleRule, DataBarRule
ws_scale = wb.create_sheet("색조")
ws_bar = wb.create_sheet("막대")
for sheet in (ws_scale, ws_bar):
for row in rows:
sheet.append(row)
for col in "BCD":
sheet.column_dimensions[col].width = 14
ws_scale.conditional_formatting.add(
"B2:D5",
ColorScaleRule(start_type="min", start_color="FFFFFF", end_type="max", end_color="63BE7B"),
)
ws_bar.conditional_formatting.add(
"B2:D5",
DataBarRule(start_type="min", end_type="max", color="5B9BD5"),
)
같은 서식을 여러 번 쓸 때: NamedStyle
합계 행처럼 같은 서식 묶음을 여러 곳에 쓴다면 NamedStyle로 이름을 붙여 두면 편하다. 엑셀의 “셀 스타일” 목록에도 그 이름으로 나타난다.
from openpyxl.styles import NamedStyle
ws.append(["합계", "=SUM(B2:B5)", "=SUM(C2:C5)", "=SUM(D2:D5)"])
total = NamedStyle(name="total")
total.font = Font(name="맑은 고딕", bold=True)
total.fill = PatternFill(fill_type="solid", start_color="F2F2F2")
total.border = Border(top=Side(style="double"))
total.number_format = "#,##0"
for cell in ws[6]:
cell.style = total
wb.save("sales_styled.xlsx")
저장한 파일을 열면 다음과 같이 보인다.

색조와 데이터 막대를 넣은 시트는 이렇게 보인다.


저장한 서식 다시 읽기
파일을 다시 열어 서식이 제대로 들어갔는지 확인해 보자.
from openpyxl import load_workbook
wb2 = load_workbook("sales_styled.xlsx")
ws2 = wb2["매출"]
print(ws2["A1"].font.bold, ws2["A1"].fill.start_color.rgb)
print(ws2["B2"].number_format, ws2.column_dimensions["B"].width)
print(ws2.freeze_panes, ws2.auto_filter.ref)
print(ws2["B6"].style, ws2["B6"].value)
True 001F4E78
#,##0 14.0
B2 A1:D5
total =SUM(B2:B5)
색이 001F4E78처럼 8자리로 나오는 것은 앞의 두 자리가 투명도이기 때문이다. 합계 칸의 값은 계산 결과가 아니라 수식 문자열로 읽힌다. 계산된 값이 필요하면 엑셀에서 한 번 열어 저장한 뒤 load_workbook(파일, data_only=True)로 읽는다.
정리
| 하고 싶은 일 | 쓰는 것 |
|---|---|
| 글꼴, 굵게, 글자색 | cell.font = Font(...) |
| 배경색 | cell.fill = PatternFill(fill_type="solid", start_color=...) |
| 정렬, 줄 바꿈 | cell.alignment = Alignment(...) |
| 테두리 | cell.border = Border(left=Side(...), ...) |
| 쉼표, 퍼센트, 날짜 | cell.number_format = "#,##0" |
| 열 너비, 행 높이 | ws.column_dimensions["A"].width, ws.row_dimensions[1].height |
| 틀 고정, 필터 | ws.freeze_panes, ws.auto_filter.ref |
| 조건부 서식 | ws.conditional_formatting.add(범위, 규칙) |
판다스 데이터프레임을 엑셀로 옮긴 뒤 서식을 입히고 싶다면 DataFrame을 엑셀에 삽입하기의 방법으로 값을 넣고, 이 글의 방법으로 꾸미면 된다.
이어서 읽기 openpyxl로 엑셀 차트 만들기
자주 묻는 질문
openpyxl에서 셀 배경색은 어떻게 넣나?
PatternFill(fill_type="solid", start_color="1F4E78")을 만들어 cell.fill에 넣는다. fill_type을 빼면 색을 지정해도 칠해지지 않는다.
cell.font.bold = True 라고 쓰면 왜 오류가 나나?
셀에 붙은 서식 객체는 고칠 수 없게 돼 있다. cell.font = Font(bold=True)처럼 새 객체를 넣거나, copy(cell.font)로 복사해서 고친 뒤 다시 넣는다.
열 너비를 내용에 맞게 자동으로 맞출 수 있나?
자동 맞춤 기능은 없다. 열마다 가장 긴 값의 글자 수를 세어 ws.column_dimensions["A"].width에 직접 넣는다. 한글은 한 글자를 2칸으로 계산하면 얼추 맞는다.
천 단위 쉼표는 어떻게 넣나?
값은 숫자 그대로 두고 cell.number_format = "#,##0"을 지정한다. 문자열로 바꿔 쉼표를 넣으면 엑셀에서 합계를 낼 수 없다.
조건부 서식을 넣었는데 파이썬에서 다시 읽으면 색이 안 보인다. 왜 그런가?
조건부 서식은 규칙만 파일에 저장되고, 색은 엑셀이 파일을 열 때 계산해서 칠한다. openpyxl로 읽은 cell.fill에는 반영되지 않는다.
참고한 문서
- https://openpyxl.readthedocs.io/en/stable/styles.html
- https://openpyxl.readthedocs.io/en/stable/formatting.html
댓글남기기