你有没有遇到过这样的问题:
老板发来一个ppt文件,里面有许多幻灯片,每张有一张数据表格,列如工资表,要求你把这些表格全部提取出来,合并成一个excel,方便后续的计算和分析。
你是不是一张一张点开幻灯片,手动复制表格,然后再粘贴到excel中去,最后还要对一些文件型数据,如“金额”“余额”,再转化为数据类型。如果这个ppt文件有几十页……加班到半夜不是梦!!!
目前就有一个这样的问题。一ppt文档中有36张幻灯片,每张幻灯片为某银行的交易流水明细。需要把所有的表格提出来,汇总为一个excel文件。

别着急用手动来解决!今天教你用python来解决。0.56秒即可搞定!
先来看代码:
from pptx import Presentation
import pandas as pd
import time
s_t = time.time()
path = r'E:1-9月工资.pptx'
prs = Presentation(path)
tables = []
for slide in prs.slides:
for shape in slide.shapes:
if shape.has_table:
table = shape.table
t=[[cell.text for cell in row.cells] for row in table.rows]
if len(t)>1:
df = pd.DataFrame(t[1:],columns=t[0])
tables.append(df)
dfs = pd.concat(tables).reset_index()
dfs["金额"] = pd.to_numeric(dfs["金额"].str.replace(",", ""),errors="coerce")
dfs["余额"] = pd.to_numeric(dfs["余额"].str.replace(",", ""),errors="coerce")
dfs.to_excel(r"E:1-9月工资.xlsx", index=False)
e_t = time.time()
print(f"共汇总{len(prs.slides)}张幻灯片
{len(dfs)}条数据
用时{e_t-s_t:.2f}秒")
再来看看运行结果:一共36张幻灯片,汇总540条数据,用时仅0.56秒。


再来看代码解析:
第1-3行:导入所需的模块
from pptx import Presentation
import pandas as pd
import time
- Presentation:用于读取pptx文件。安装方法为win+r打开“运行”,输入“cmd”回车后输入“pip install python-pptx”再回车即可自动安装。
- pandas:用于表格数据的处理,安装方法:pip install pandas。
- time:用于计算运行时间。
第5-8行:加载ppt文件
s_t = time.time()
path = r'E:1-9月工资.pptx'
prs = Presentation(path)
tables = []
- s_t = time.time():开始计时
- prs = Presentation(path):使用Presentation()加载指定路径的ppt文件。
- tables = []:空列表,用于存入所有表格数据
第9-16行:遍历每一张幻灯片,查找表格
for slide in prs.slides:
for shape in slide.shapes:
if shape.has_table:
table = shape.table
t=[[cell.text for cell in row.cells] for row in table.rows]
if len(t)>1:
df = pd.DataFrame(t[1:],columns=t[0])
tables.append(df)
- for slide in prs.slides:遍历每一张幻灯片。prs.slides为所有幻灯片的集合。
- for shape in slide.shapes:遍历幻灯片中所有的对象。
- if shape.has_table:判断这个形状是不是表格,如果是表格则运行下面的代码。
- table = shape.table:获取这个表格对象。
- t=[[cell.text for cell in row.cells] for row in table.rows]:提取表格数据,第一行为列名,其余为数据。
- if len(t)>1:如果表格行数大于1行,确保表格至少有1行数据。
- df = pd.DataFrame(t[1:],columns=t[0]):转化为DataFrame,columns=t[0]表明第一行为标题行,t[1:]表明第一行后的内容为数据。
- tables.append(df):把生成的df添加到列表。
第18-20行:合并数据,转换数据类型
dfs = pd.concat(tables).reset_index()
dfs["金额"] = pd.to_numeric(dfs["金额"].str.replace(",", ""),errors="coerce")
dfs["余额"] = pd.to_numeric(dfs["余额"].str.replace(",", ""),errors="coerce")
- pd.concat(tables).reset_index():使用.concat()一次性合并tables所有数据,并重置索引。
- pd.to_numeric(dfs[“金额”].str.replace(“,”, “”), errors=”coerce”) :清洗数据,去掉逗号,转为数字。
第22-24行:保存结果,显示汇总信息
dfs.to_excel(r"E:1-9月工资.xlsx", index=False)
e_t = time.time()
print(f"共汇总{len(prs.slides)}张幻灯片
{len(dfs)}条数据
用时{e_t-s_t:.2f}秒")
- dfs.to_excel(r”E:1-9月工资.xlsx”, index=False):使用.to_excel()方法保存文件,不保留索引。
- e_t = time.time():结束计时。
- print(f”共汇总{len(prs.slides)}张幻灯片
{len(dfs)}条数据
用时{e_t-s_t:.2f}秒”):显示汇总信息和运行时长。
恰当的运用代码,可以让你的工作效率明显提升,并且准确性极高、可以重复使用,还能灵活扩展。如果你也有此类问题只需稍作修改即可使用。
希望这个案例能够对你有所协助!关注我,获取更多实用办公自动化技巧吧~~~

© 版权声明
文章版权归作者所有,未经允许请勿转载。如内容涉嫌侵权,请在本页底部进入<联系我们>进行举报投诉!
THE END













暂无评论内容