假设有 11 个 PPT,每个 PPT 里面有若干张幻灯片包含表格。Python 自动遍历所有 PPT,找到表格,将表格数据逐一提取出来,按照原有顺序汇总到一个新的 Excel 文件。
PPT 原始内容 | Excel 中的处理 |
|---|---|
单元格文字 | 保留 |
字体、字号、粗体 | 尽量保留 |
字体颜色 | 保留 |
单元格背景颜色 | 保留 |
边框颜色和样式 | 尽量保留 |
水平、垂直对齐 | 保留 |
单元格宽度和高度 | 尽量映射 |
合并单元格 | 尽量保留 |
图片 | 可以提取并插入 |
公式 | PPT 普通表格通常没有原生 Excel 公式 |
import os
import re
import win32com.client
from openpyxl import Workbook
from openpyxl.styles import Font, PatternFill, Border, Side, Alignment
from openpyxl.utils import get_column_letter
# ==============================
# 1. 配置
# ==============================
FOLDER = r"D:\PPT_Merge"
OUTPUT = os.path.join(FOLDER, "PPT表格汇总.xlsx")
# 是否保留每张表格自己的表头
KEEP_HEADERS = True
# 表格之间空几行
TABLE_GAP = 1
# ==============================
# 2. 辅助函数
# ==============================
def natural_sort_key(text):
"""按文件名中的数字自然排序"""
return [
int(x) if x.isdigit() else x.lower()
for x in re.split(r"(\d+)", text)
]
def ppt_rgb_to_hex(rgb):
"""将 PowerPoint RGB 整数转换为 Excel HEX"""
try:
rgb = int(rgb)
r = rgb & 255
g = (rgb >> 8) & 255
b = (rgb >> 16) & 255
return f"{r:02X}{g:02X}{b:02X}"
except Exception:
return None
def safe_get(func, default=None):
"""读取 COM 属性,避免个别特殊格式导致程序中断"""
try:
return func()
except Exception:
return default
def get_border(cell, border_id):
"""读取 PowerPoint 单元格边框"""
try:
line = cell.Borders(border_id)
visible = line.Visible
if not visible:
return Side(style=None)
color = ppt_rgb_to_hex(line.ForeColor.RGB)
return Side(
style="thin",
color=color or "000000"
)
except Exception:
return Side(style=None)
def get_cell_text(cell):
"""获取 PPT 单元格文字"""
try:
return cell.Shape.TextFrame.TextRange.Text.rstrip("\r\x0b")
except Exception:
return ""
# ==============================
# 3. 读取单元格格式
# ==============================
def copy_cell_format(ppt_cell, excel_cell):
shape = ppt_cell.Shape
# 字体格式
text_range = safe_get(
lambda: shape.TextFrame.TextRange
)
if text_range is not None:
font = text_range.Font
font_name = safe_get(lambda: font.Name)
font_size = safe_get(lambda: font.Size)
bold = safe_get(lambda: font.Bold, False)
italic = safe_get(lambda: font.Italic, False)
underline = safe_get(lambda: font.Underline, False)
font_color = safe_get(lambda: font.Color.RGB)
excel_cell.font = Font(
name=font_name,
size=font_size,
bold=bool(bold),
italic=bool(italic),
underline="single" if underline else None,
color=ppt_rgb_to_hex(font_color)
)
# 水平对齐
paragraph_alignment = safe_get(
lambda: text_range.ParagraphFormat.Alignment
)
alignment_map = {
1: "left",
2: "center",
3: "right",
4: "justify",
}
horizontal = alignment_map.get(
paragraph_alignment, "left"
)
# 垂直对齐
vertical_anchor = safe_get(
lambda: shape.TextFrame.VerticalAnchor
)
vertical_map = {
1: "top",
3: "center",
4: "bottom",
}
vertical = vertical_map.get(
vertical_anchor, "center"
)
excel_cell.alignment = Alignment(
horizontal=horizontal,
vertical=vertical,
wrap_text=True
)
# 背景颜色
try:
fill = shape.Fill
if fill.Visible:
fill_type = fill.Type
# 仅对纯色填充直接复制背景颜色
if fill_type == 1:
color = ppt_rgb_to_hex(fill.ForeColor.RGB)
if color:
excel_cell.fill = PatternFill(
fill_type="solid",
fgColor=color
)
except Exception:
pass
# 单元格边框
# PowerPoint 边框常量:
# 1 = Top, 2 = Left, 3 = Bottom, 4 = Right
excel_cell.border = Border(
top=get_border(ppt_cell, 1),
left=get_border(ppt_cell, 2),
bottom=get_border(ppt_cell, 3),
right=get_border(ppt_cell, 4)
)
# ==============================
# 4. 提取 PPT 表格
# ==============================
def extract_tables(presentation, filename, worksheet):
table_count = 0
for slide_index in range(1, presentation.Slides.Count + 1):
slide = presentation.Slides(slide_index)
for shape_index in range(1, slide.Shapes.Count + 1):
shape = slide.Shapes(shape_index)
# 判断是否为真正的 PowerPoint 表格
if not shape.HasTable:
continue
table = shape.Table
rows = table.Rows.Count
cols = table.Columns.Count
print(
f"发现表格:{filename} "
f"第{slide_index}页 "
f"{rows}行×{cols}列"
)
table_count += 1
# 来源标记
source_row = worksheet.max_row + 1
worksheet.merge_cells(
start_row=source_row,
start_column=1,
end_row=source_row,
end_column=cols
)
source_cell = worksheet.cell(
row=source_row,
column=1,
value=f"来源:{filename} | 第{slide_index}页 | 表格{table_count}"
)
source_cell.font = Font(
bold=True,
color="FFFFFF",
size=10
)
source_cell.fill = PatternFill(
fill_type="solid",
fgColor="4472C4"
)
source_cell.alignment = Alignment(
horizontal="left",
vertical="center"
)
worksheet.row_dimensions[source_row].height = 22
# 表格数据开始位置
start_row = source_row + 1
# 逐行提取
for r in range(1, rows + 1):
for c in range(1, cols + 1):
ppt_cell = table.Cell(r, c)
value = get_cell_text(ppt_cell)
excel_cell = worksheet.cell(
row=start_row + r - 1,
column=c,
value=value
)
# 复制格式
copy_cell_format(
ppt_cell,
excel_cell
)
# 尽量保留行高
try:
height = table.Rows(r).Height
worksheet.row_dimensions[
start_row + r - 1
].height = height
except Exception:
pass
# 尽量保留列宽
for c in range(1, cols + 1):
try:
width = table.Columns(c).Width
# PowerPoint 宽度单位为 point
# Excel 列宽为近似字符宽度
excel_width = width / 5.25
col_letter = get_column_letter(c)
current_width = worksheet.column_dimensions[
col_letter
].width
if current_width is None or excel_width > current_width:
worksheet.column_dimensions[
col_letter
].width = excel_width
except Exception:
pass
# 下一张表格之前留空行
next_row = start_row + rows + TABLE_GAP
worksheet.cell(
row=next_row - 1,
column=1,
value=None
)
return table_count
# ==============================
# 5. 主程序
# ==============================
def main():
files = sorted(
[
os.path.join(FOLDER, f)
for f in os.listdir(FOLDER)
if f.lower().endswith(".pptx")
and f.lower() != os.path.basename(OUTPUT).lower()
and not f.startswith("~$")
],
key=lambda x: natural_sort_key(os.path.basename(x))
)
if not files:
raise RuntimeError("没有找到 PPTX 文件")
# 创建 Excel
wb = Workbook()
ws = wb.active
ws.title = "汇总"
# 设置工作表
ws.freeze_panes = "A1"
app = win32com.client.DispatchEx(
"PowerPoint.Application"
)
app.Visible = True
total_tables = 0
total_files = 0
try:
for index, ppt_path in enumerate(files, 1):
filename = os.path.basename(ppt_path)
print("\n" + "=" * 50)
print(f"[{index}/{len(files)}] 正在处理:{filename}")
presentation = None
try:
presentation = app.Presentations.Open(
ppt_path,
ReadOnly=True,
Untitled=False,
WithWindow=False
)
count = extract_tables(
presentation,
filename,
ws
)
total_tables += count
total_files += 1
print(f"提取完成:{count} 个表格")
except Exception as e:
print(f"处理失败:{filename}")
print("错误信息:", e)
finally:
if presentation is not None:
presentation.Close()
# 保存 Excel
wb.save(OUTPUT)
print("\n" + "=" * 50)
print("全部处理结束!")
print("成功处理 PPT:", total_files)
print("提取表格数量:", total_tables)
print("Excel 保存位置:", OUTPUT)
finally:
app.Quit()
if __name__ == "__main__":
main()
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。