Python实现将Word和Excel文件转换为PPT!
Python实现将Word和Excel文件转换为PPT!
在日常工作中,我们经常需要将多个Word文档或Excel表格的内容汇总到一个PPT演示文稿中,手动执行这项任务可能非常耗时,因此,使用Python自动化这个过程可以大大提高效率,所以本文给大家介绍了Python实现将Word和Excel文件转换为PPT,需要的朋友可以参考下。
前言
在日常工作中,我们经常需要将多个Word文档或Excel表格的内容汇总到一个PPT演示文稿中。手动执行这项任务可能非常耗时,因此,使用Python自动化这个过程可以大大提高效率。在这篇博客中,我将介绍如何使用wxPython创建一个图形用户界面(GUI),选择文件夹、遍历文件,并将Word和Excel文档的内容导出为PPT文件。
环境准备
在开始之前,确保已安装以下Python库:
- wxPython:用于创建图形用户界面。
- python-pptx:用于生成PowerPoint文件。
- pywin32:用于与Word和Excel文件进行交互。
使用以下命令安装这些依赖项:
| 1 | pip installwxPython python-pptx pywin32 | 
功能需求
该应用程序的核心功能如下:
- 选择文件夹并遍历文件:用户可以选择一个包含Word和Excel文件的文件夹,程序会自动遍历所有文件并将其显示在一个列表框(ListBox)中。
- 文件排序:用户可以通过拖拽调整文件在列表中的顺序。
- 导出到PPT:点击导出按钮后,程序会将列表框中的文件按照顺序,每个文件的内容插入一个PPT页面,并将生成的PPT文件保存在相同的文件夹中。
程序实现
以下是完整的代码实现:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 | importwximportosfrompptx importPresentationfrompptx.util importInchesfromwin32com.client importDispatchimportpythoncomclassFilePickerApp(wx.Frame):def__init__(self, parent, title):super(FilePickerApp, self).__init__(parent, title=title, size=(800, 600))panel =wx.Panel(self)# Create buttons and ListBoxself.select_folder_btn =wx.Button(panel, label="Select Folder", pos=(10, 10))self.export_btn =wx.Button(panel, label="Export to PPT", pos=(680, 10))self.file_listbox =wx.ListBox(panel, pos=(10, 50), size=(760, 450), style=wx.LB_SINGLE)# Bind eventsself.select_folder_btn.Bind(wx.EVT_BUTTON, self.on_select_folder)self.export_btn.Bind(wx.EVT_BUTTON, self.on_export)# Enable drag-and-drop reordering in ListBoxself.file_listbox.Bind(wx.EVT_LISTBOX_DCLICK, self.on_drag_drop)self.Show()defon_select_folder(self, event):with wx.DirDialog(self, "Select a folder", style=wx.DD_DEFAULT_STYLE) as dlg:ifdlg.ShowModal() ==wx.ID_OK:folder_path =dlg.GetPath()self.populate_listbox(folder_path)defpopulate_listbox(self, folder_path):self.file_listbox.Clear()forroot, dirs, files inos.walk(folder_path):forfileinfiles:iffile.endswith(('.docx', '.xlsx')):self.file_listbox.Append(os.path.join(root, file))defon_drag_drop(self, event):# Implement drag-and-drop reorderingselected =self.file_listbox.GetSelection()ifselected !=wx.NOT_FOUND:item =self.file_listbox.GetString(selected)dlg =wx.TextEntryDialog(self, 'Reorder:', 'Enter new position', str(selected +1))ifdlg.ShowModal() ==wx.ID_OK:new_pos =int(dlg.GetValue()) -1self.file_listbox.Delete(selected)self.file_listbox.InsertItems([item], new_pos)dlg.Destroy()defon_export(self, event):file_paths =self.file_listbox.GetItems()iffile_paths:prs =Presentation()forfile_path infile_paths:slide =prs.slides.add_slide(prs.slide_layouts[5])shape =slide.shapes.add_textbox(Inches(1), Inches(1), Inches(8), Inches(5.5))try:iffile_path.endswith('.docx'):pythoncom.CoInitialize()word =Dispatch('Word.Application')word.Visible =Falsedoc =word.Documents.Open(file_path)text =doc.Content.Textdoc.Close()word.Quit()eliffile_path.endswith('.xlsx'):pythoncom.CoInitialize()excel =Dispatch('Excel.Application')excel.Visible =Falsewb =excel.Workbooks.Open(file_path)ws =wb.Worksheets(1)text ='\n'.join(['\t'.join([str(cell) forcell inrow]) forrow inws.UsedRange.Value])wb.Close()excel.Quit()shape.text =textexceptException as e:wx.MessageBox(f"Failed to process file {file_path}.\nError: {str(e)}", "Error", wx.OK | wx.ICON_ERROR)continuesave_path =os.path.join(os.path.dirname(file_paths[0]), 'exported_presentation.pptx')prs.save(save_path)wx.MessageBox(f"PPT exported to {save_path}", "Export Success", wx.OK | wx.ICON_INFORMATION)if__name__ =='__main__':app =wx.App(False)frame =FilePickerApp(None, "File to PPT Exporter")app.MainLoop() | 
代码解析
- 用户界面:使用wxPython创建了一个简单的GUI,其中包含一个选择文件夹的按钮、一个用于显示文件的ListBox、和一个用于导出PPT的按钮。
- 选择文件夹:通过wx.DirDialog,用户可以选择一个包含Word和Excel文件的文件夹。程序会自动遍历该文件夹及其子文件夹,并将所有Word和Excel文件添加到ListBox中。
- 拖拽排序:通过双击ListBox中的某个文件,用户可以输入新位置,调整文件的顺序。
- 导出PPT:当用户点击“导出为PPT”按钮时,程序会将ListBox中的文件内容按照顺序插入到PPT的每个页面,并将生成的PPT文件保存在相同的文件夹中。
错误处理
在导出PPT的过程中,可能会遇到各种错误,例如文件路径错误或Word/Excel应用程序无法启动。为此,我们添加了错误处理逻辑,确保在发生错误时,用户会收到错误信息,并且程序不会崩溃。
结果如下

总结
这篇博客展示了如何使用wxPython结合python-pptx和pywin32,通过图形界面将多个Word和Excel文件的内容自动化地导出为PPT演示文稿。通过这种方法,你可以显著提高工作效率,避免繁琐的手动操作。
学习资料见知识星球。
以上就是今天要分享的技巧,你学会了吗?若有什么问题,欢迎在下方留言。
快来试试吧,小琥 my21ke007。获取 1000个免费 Excel模板福利!
更多技巧, www.excelbook.cn
欢迎 加入 零售创新 知识星球,知识星球主要以数据分析、报告分享、数据工具讨论为主;
1、价值上万元的专业的PPT报告模板。
2、专业案例分析和解读笔记。
3、实用的Excel、Word、PPT技巧。
4、VIP讨论群,共享资源。
5、优惠的会员商品。
6、一次付费只需129元,即可下载本站文章涉及的文件和软件。
