在日常工作中,我们经常需要将多个Word文档或Excel表格的内容汇总到一个PPT演示文稿中。手动执行这项任务可能非常耗时,因此,使用Python自动化这个过程可以大大提高效率。在这篇博客中,我将介绍如何使用wxPython
创建一个图形用户界面(GUI),选择文件夹、遍历文件,并将Word和Excel文档的内容导出为PPT文件。
C:\pythoncode\new\wordexcelToPPT.py
环境准备
在开始之前,确保已安装以下Python库:
wxPython
:用于创建图形用户界面。python-pptx
:用于生成PowerPoint文件。pywin32
:用于与Word和Excel文件进行交互。
使用以下命令安装这些依赖项:
pip install wxPython python-pptx pywin32
功能需求
该应用程序的核心功能如下:
-
选择文件夹并遍历文件:用户可以选择一个包含Word和Excel文件的文件夹,程序会自动遍历所有文件并将其显示在一个列表框(ListBox)中。
-
文件排序:用户可以通过拖拽调整文件在列表中的顺序。
-
导出到PPT:点击导出按钮后,程序会将列表框中的文件按照顺序,每个文件的内容插入一个PPT页面,并将生成的PPT文件保存在相同的文件夹中。
程序实现
以下是完整的代码实现:
import wx
import os
from pptx import Presentation
from pptx.util import Inches
from win32com.client import Dispatch
import pythoncom
class FilePickerApp(wx.Frame):
def __init__(self, parent, title):
super(FilePickerApp, self).__init__(parent, title=title, size=(800, 600))
panel = wx.Panel(self)
# Create buttons and ListBox
self.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 events
self.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 ListBox
self.file_listbox.Bind(wx.EVT_LISTBOX_DCLICK, self.on_drag_drop)
self.Show()
def on_select_folder(self, event):
with wx.DirDialog(self, "Select a folder", style=wx.DD_DEFAULT_STYLE) as dlg:
if dlg.ShowModal() == wx.ID_OK:
folder_path = dlg.GetPath()
self.populate_listbox(folder_path)
def populate_listbox(self, folder_path):
self.file_listbox.Clear()
for root, dirs, files in os.walk(folder_path):
for file in files:
if file.endswith(('.docx', '.xlsx')):
self.file_listbox.Append(os.path.join(root, file))
def on_drag_drop(self, event):
# Implement drag-and-drop reordering
selected = self.file_listbox.GetSelection()
if selected != wx.NOT_FOUND:
item = self.file_listbox.GetString(selected)
dlg = wx.TextEntryDialog(self, 'Reorder:', 'Enter new position', str(selected + 1))
if dlg.ShowModal() == wx.ID_OK:
new_pos = int(dlg.GetValue()) - 1
self.file_listbox.Delete(selected)
self.file_listbox.InsertItems([item], new_pos)
dlg.Destroy()
def on_export(self, event):
file_paths = self.file_listbox.GetItems()
if file_paths:
prs = Presentation()
for file_path in file_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:
if file_path.endswith('.docx'):
pythoncom.CoInitialize()
word = Dispatch('Word.Application')
word.Visible = False
doc = word.Documents.Open(file_path)
text = doc.Content.Text
doc.Close()
word.Quit()
elif file_path.endswith('.xlsx'):
pythoncom.CoInitialize()
excel = Dispatch('Excel.Application')
excel.Visible = False
wb = excel.Workbooks.Open(file_path)
ws = wb.Worksheets(1)
text = '\n'.join(['\t'.join([str(cell) for cell in row]) for row in ws.UsedRange.Value])
wb.Close()
excel.Quit()
shape.text = text
except Exception as e:
wx.MessageBox(f"Failed to process file {file_path}.\nError: {str(e)}", "Error", wx.OK | wx.ICON_ERROR)
continue
save_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演示文稿。通过这种方法,你可以显著提高工作效率,避免繁琐的手动操作。