python-pptx 표 넣기 - 셀 서식, 열 너비, 셀 병합, 데이터프레임을 PPT 표로
python-pptx로 표를 넣으려면 slide.shapes.add_table(행 수, 열 수, 왼쪽, 위, 너비, 높이).table로 표를 만들고 table.cell(행, 열).text에 값을 넣는다. 글꼴 크기와 정렬은 셀 안의 문단(paragraph)에, 배경색은 셀(cell.fill)에, 너비는 열(table.columns[i].width)에 지정한다. 슬라이드를 만드는 기본 사용법은 python-pptx 파이썬으로 파워포인트 이용하기에 있고, 이 글은 보고서에 쓸 만한 표를 만드는 데 집중한다.
이 글의 코드는 python-pptx 1.0.2, pandas 3.1.2에서 실행해 확인했고, 코드 아래의 결과는 실제 출력이다. 슬라이드 그림은 만들어진 파일을 LibreOffice로 열어 저장한 것이라 파워포인트에서 볼 때와 글꼴이 조금 다를 수 있다.
한눈에 보기
| 하고 싶은 일 | 코드 |
|---|---|
| 표 넣기 | slide.shapes.add_table(rows, cols, x, y, w, h).table |
| 값 넣기 | table.cell(r, c).text = "값" |
| 글꼴 크기, 굵게 | paragraph.font.size = Pt(12), paragraph.font.bold = True |
| 가로 정렬 | paragraph.alignment = PP_ALIGN.RIGHT |
| 세로 정렬 | cell.vertical_anchor = MSO_ANCHOR.MIDDLE |
| 배경색 | cell.fill.solid(), cell.fill.fore_color.rgb = RGBColor(...) |
| 열 너비, 행 높이 | table.columns[i].width, table.rows[i].height |
| 셀 병합 | table.cell(0, 0).merge(table.cell(0, 2)) |
설치
pip install python-pptx pandas
python-pptx 표 넣기
제목만 있는 슬라이드(레이아웃 5번)에 4행 4열 표를 넣는다. 위치와 크기는 Inches(인치)나 Cm(센티미터)로 준다.
from pptx import Presentation
from pptx.util import Inches, Pt
prs = Presentation()
slide = prs.slides.add_slide(prs.slide_layouts[5])
slide.shapes.title.text = "지점별 매출"
rows = [
["지점", "1월", "2월", "3월"],
["강남", 1250000, 1380000, 990000],
["홍대", 870000, 910000, 1120000],
["잠실", 1430000, 1205000, 1510000],
]
frame = slide.shapes.add_table(len(rows), len(rows[0]), Inches(0.5), Inches(1.8), Inches(9), Inches(2))
table = frame.table
for r, row in enumerate(rows):
for c, value in enumerate(row):
table.cell(r, c).text = f"{value:,}" if isinstance(value, int) else value
prs.save("table_basic.pptx")
print(len(table.rows), len(table.columns), table.cell(1, 1).text)
4 4 1,250,000
cell.text에는 문자열만 넣을 수 있다. 숫자는 f"{value:,}"처럼 천 단위 쉼표를 붙인 문자열로 바꿔 넣는다. 첫 행은 기본 표 스타일 때문에 자동으로 머리글 색이 칠해진다.

셀 글자 정렬, 글꼴 크기, 배경색 바꾸기
셀 하나의 글자 서식은 셀 안의 문단마다 지정한다. cell.text로 넣은 글은 문단 하나다. 숫자 열은 오른쪽, 머리글은 가운데 정렬하고, 머리글 배경을 남색으로 칠한다.
from pptx.dml.color import RGBColor
from pptx.enum.text import PP_ALIGN, MSO_ANCHOR
def style_cell(cell, size=14, bold=False, align=PP_ALIGN.LEFT, fill=None, color=None):
cell.vertical_anchor = MSO_ANCHOR.MIDDLE # 세로 가운데
for paragraph in cell.text_frame.paragraphs:
paragraph.alignment = align
paragraph.font.size = Pt(size)
paragraph.font.bold = bold
if color:
paragraph.font.color.rgb = color
if fill:
cell.fill.solid()
cell.fill.fore_color.rgb = fill
navy, white = RGBColor(0x1F, 0x4E, 0x78), RGBColor(0xFF, 0xFF, 0xFF)
for r in range(len(table.rows)):
for c in range(len(table.columns)):
cell = table.cell(r, c)
if r == 0:
style_cell(cell, size=14, bold=True, align=PP_ALIGN.CENTER, fill=navy, color=white)
else:
style_cell(cell, size=13, align=PP_ALIGN.RIGHT if c > 0 else PP_ALIGN.CENTER)
prs.save("table_style.pptx")
print(table.cell(1, 1).text_frame.paragraphs[0].alignment)
RIGHT (3)
줄무늬 배경(한 행씩 번갈아 칠하는 것)은 table.horz_banding = False로 끌 수 있고, 첫 행 머리글 서식은 table.first_row = False로 끈다.
열 너비와 행 높이 지정하기
처음에는 표 너비가 열 개수로 똑같이 나뉜다. 지점 이름 열은 좁게, 숫자 열은 넓게 바꾼다.
from pptx.util import Emu
table.columns[0].width = Inches(1.5)
for c in range(1, 4):
table.columns[c].width = Inches(2.3)
for r in range(len(table.rows)):
table.rows[r].height = Inches(0.5)
total = sum(col.width for col in table.columns)
print(Emu(total).inches, frame.width.inches)
prs.save("table_style.pptx")
8.4 8.4
열 너비의 합(8.4인치)이 표 도형(frame)의 너비가 됐다. 처음 add_table()에 준 9인치는 열을 처음 나눌 때만 쓰인다. 표를 가운데에 두고 싶으면 frame.left = (prs.slide_width - frame.width) // 2처럼 위치를 다시 계산한다.

셀 병합하기
“상반기 실적”처럼 여러 열을 묶는 제목 칸이 필요할 때 셀을 합친다. 왼쪽 위 셀에서 merge()에 오른쪽 아래 셀을 주면 그 사이 칸이 모두 합쳐진다.
prs = Presentation()
slide = prs.slides.add_slide(prs.slide_layouts[5])
slide.shapes.title.text = "셀 병합"
table = slide.shapes.add_table(4, 4, Inches(0.5), Inches(1.8), Inches(9), Inches(2)).table
table.cell(0, 0).merge(table.cell(1, 0)) # 1열: 위아래 두 칸
table.cell(0, 1).merge(table.cell(0, 3)) # 1행: 2~4열
table.cell(0, 0).text = "지점"
table.cell(0, 1).text = "1분기 매출"
for c, month in enumerate(["1월", "2월", "3월"], start=1):
table.cell(1, c).text = month
for r, row in enumerate([["강남", "125", "138", "99"], ["홍대", "87", "91", "112"]], start=2):
for c, value in enumerate(row):
table.cell(r, c).text = value
for r in range(4):
for c in range(4):
cell = table.cell(r, c)
if not cell.is_spanned: # 합쳐져 가려진 칸은 건너뛴다
style_cell(cell, align=PP_ALIGN.CENTER)
prs.save("table_merge.pptx")
first = table.cell(0, 1)
print(first.is_merge_origin, first.span_width, table.cell(0, 2).is_spanned)
True 3 True
합친 칸의 값은 왼쪽 위 셀(is_merge_origin)에 넣는다. 가려진 칸(is_spanned)에 넣은 값은 화면에 보이지 않는다. 합친 것을 풀려면 왼쪽 위 셀에서 cell.split()을 부른다.

판다스 데이터프레임을 PPT 표로 넣기
실무에서는 판다스로 계산한 결과를 그대로 표로 옮기는 일이 많다. 데이터프레임을 받아 표를 만드는 함수를 만들어 두면 편하다. 숫자 열은 쉼표를 붙여 오른쪽 정렬한다.
import pandas as pd
def add_df_table(slide, df, x=Inches(0.5), y=Inches(1.6), width=Inches(9), row_height=Inches(0.4),
font_size=12, col_widths=None):
n_rows, n_cols = len(df) + 1, len(df.columns)
frame = slide.shapes.add_table(n_rows, n_cols, x, y, width, row_height * n_rows)
table = frame.table
if col_widths:
for c, w in enumerate(col_widths):
table.columns[c].width = w
for c, name in enumerate(df.columns):
table.cell(0, c).text = str(name)
style_cell(table.cell(0, c), size=font_size, bold=True, align=PP_ALIGN.CENTER, fill=navy, color=white)
for r, row in enumerate(df.itertuples(index=False), start=1):
for c, value in enumerate(row):
is_num = isinstance(value, (int, float)) and not isinstance(value, bool)
table.cell(r, c).text = f"{value:,.0f}" if is_num else str(value)
style_cell(table.cell(r, c), size=font_size, align=PP_ALIGN.RIGHT if is_num else PP_ALIGN.LEFT)
return table
df = pd.DataFrame({
"단지": ["래미안", "자이", "힐스테이트", "푸르지오", "아이파크"],
"전용면적": [84.9, 59.9, 84.9, 114.8, 84.9],
"거래금액(만원)": [215000, 138000, 189500, 262000, 177000],
"층": [12, 7, 21, 15, 3],
})
prs = Presentation()
slide = prs.slides.add_slide(prs.slide_layouts[5])
slide.shapes.title.text = "이번 달 실거래"
table = add_df_table(slide, df, col_widths=[Inches(3), Inches(2), Inches(2.5), Inches(1.5)])
prs.save("table_df.pptx")
print([table.cell(1, c).text for c in range(4)])
['래미안', '85', '215,000', '12']
전용면적 84.9가 85로 반올림됐다. {value:,.0f}가 소수점을 버리기 때문이다. 소수점이 필요한 열이 있다면 열마다 형식을 다르게 줘야 한다. 형식을 함수 인자로 받게 고치거나, 넣기 전에 데이터프레임에서 문자열로 바꿔 두면 된다.
df_text = df.assign(전용면적=df["전용면적"].map("{:.1f}㎡".format))
prs = Presentation()
slide = prs.slides.add_slide(prs.slide_layouts[5])
slide.shapes.title.text = "이번 달 실거래"
table = add_df_table(slide, df_text, col_widths=[Inches(3), Inches(2), Inches(2.5), Inches(1.5)])
prs.save("table_df.pptx")
print([table.cell(1, c).text for c in range(4)])
['래미안', '84.9㎡', '215,000', '12']
문자열로 바꾼 열은 왼쪽 정렬된다. 숫자처럼 오른쪽에 붙이고 싶으면 style_cell()로 그 열만 다시 정렬한다.

행이 많을 때 여러 슬라이드로 나누기
표는 슬라이드 밖으로 넘쳐도 자동으로 나뉘지 않는다. 한 슬라이드에 들어갈 행 수를 정해 데이터프레임을 잘라 슬라이드마다 표를 넣는다. 머리글은 슬라이드마다 다시 넣는다.
big = pd.DataFrame({
"순위": range(1, 24),
"지역": [f"지역{i:02d}" for i in range(1, 24)],
"거래량": [1000 - i * 37 for i in range(23)],
})
def add_df_slides(prs, df, title, rows_per_slide=10):
pages = range(0, len(df), rows_per_slide)
for n, start in enumerate(pages, 1):
part = df.iloc[start:start + rows_per_slide]
slide = prs.slides.add_slide(prs.slide_layouts[5])
slide.shapes.title.text = f"{title} ({n}/{len(pages)})"
add_df_table(slide, part, row_height=Inches(0.42))
prs = Presentation()
add_df_slides(prs, big, "지역별 거래량", rows_per_slide=10)
prs.save("table_split.pptx")
print(len(prs.slides), [s.shapes.title.text for s in prs.slides])
3 ['지역별 거래량 (1/3)', '지역별 거래량 (2/3)', '지역별 거래량 (3/3)']
23행이 10행, 10행, 3행으로 세 슬라이드에 나뉘었다. 4:3 기본 슬라이드에 글꼴 12pt, 행 높이 0.42인치로 10행을 넣으면 아래에 여유가 조금 남는다(아래 그림). 글꼴과 행 높이를 바꾸면 rows_per_slide도 다시 맞춘다.

자주 겪는 문제
글꼴 크기를 줬는데 행 높이가 줄지 않는다
행 높이는 “최소 높이”다. 글자가 크거나 셀 안 여백이 크면 행이 저절로 늘어난다. 줄이려면 글꼴을 줄이거나 cell.margin_top, cell.margin_bottom을 Pt(2)처럼 작게 준다.
한글 글꼴을 지정하고 싶다
paragraph.font.name = "맑은 고딕"으로 지정한다. 다만 이 값은 라틴 글꼴 칸에 들어가서 파워포인트에 따라 한글에는 다른 글꼴이 쓰일 수 있다. 회사 양식이 있다면 양식 파일의 표 스타일과 테마 글꼴을 쓰는 편이 확실하다.
이미 있는 PPT의 표 찾기
슬라이드의 도형 중 shape.has_table이 참인 것이 표다.
prs = Presentation("table_df.pptx")
for shape in prs.slides[0].shapes:
if shape.has_table:
t = shape.table
print(shape.name, len(t.rows), len(t.columns), t.cell(0, 2).text)
Table 2 6 4 거래금액(만원)
같은 양식의 표에서 값만 매번 바꾸는 일이라면 PPT 템플릿 텍스트 일괄 바꾸기의 방법이 더 편하다. 숫자를 표 대신 그래프로 보여 주려면 python-pptx로 파워포인트에 차트 넣기를 보면 된다.
자주 묻는 질문
python-pptx에서 표는 어떻게 넣나?
slide.shapes.add_table(행 수, 열 수, 왼쪽, 위, 너비, 높이)로 표 도형을 넣고 .table로 표를 얻는다. 값은 table.cell(행, 열).text = "값"으로 넣는다.
표 셀의 글꼴 크기와 정렬은 어떻게 바꾸나?
셀의 text_frame.paragraphs를 돌며 paragraph.font.size = Pt(12), paragraph.alignment = PP_ALIGN.CENTER를 지정한다. 세로 정렬은 cell.vertical_anchor = MSO_ANCHOR.MIDDLE이다.
셀 병합은 어떻게 하나?
table.cell(0, 0).merge(table.cell(0, 2))처럼 왼쪽 위 셀에서 오른쪽 아래 셀까지 합친다. 값은 왼쪽 위 셀에 넣는다.
판다스 데이터프레임을 PPT 표로 넣을 수 있나?
직접 넣는 함수는 없다. df.columns를 머리글 행에, df.itertuples()로 각 행을 셀에 채우는 작은 함수를 만들어 쓴다. 이 글의 add_df_table()을 그대로 쓰면 된다.
열 너비를 바꿨는데 표 전체 너비가 달라진다.
python-pptx의 표 너비는 열 너비의 합이다. add_table()에 준 너비는 열을 처음 똑같이 나눌 때만 쓰이므로, 열 너비를 바꿀 때는 합이 원하는 표 너비가 되도록 나눠 준다.
참고한 문서
- https://python-pptx.readthedocs.io/en/latest/user/table.html
- https://python-pptx.readthedocs.io/en/latest/api/table.html
댓글남기기