当前位置: 代码网 > it编程>前端脚本>Python > Python实现将Word和Excel文件转换为PPT

Python实现将Word和Excel文件转换为PPT

2024年08月11日 Python 我要评论
前言在日常工作中,我们经常需要将多个word文档或excel表格的内容汇总到一个ppt演示文稿中。手动执行这项任务可能非常耗时,因此,使用python自动化这个过程可以大大提高效率。在这篇博客中,我将

前言

在日常工作中,我们经常需要将多个word文档或excel表格的内容汇总到一个ppt演示文稿中。手动执行这项任务可能非常耗时,因此,使用python自动化这个过程可以大大提高效率。在这篇博客中,我将介绍如何使用wxpython创建一个图形用户界面(gui),选择文件夹、遍历文件,并将word和excel文档的内容导出为ppt文件。

环境准备

在开始之前,确保已安装以下python库:

  • wxpython:用于创建图形用户界面。
  • python-pptx:用于生成powerpoint文件。
  • pywin32:用于与word和excel文件进行交互。

使用以下命令安装这些依赖项:

pip install wxpython python-pptx pywin32

功能需求

该应用程序的核心功能如下:

  1. 选择文件夹并遍历文件:用户可以选择一个包含word和excel文件的文件夹,程序会自动遍历所有文件并将其显示在一个列表框(listbox)中。

  2. 文件排序:用户可以通过拖拽调整文件在列表中的顺序。

  3. 导出到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-pptxpywin32,通过图形界面将多个word和excel文件的内容自动化地导出为ppt演示文稿。通过这种方法,你可以显著提高工作效率,避免繁琐的手动操作。

以上就是python实现将word和excel文件转换为ppt的详细内容,更多关于python word和excel转为ppt的资料请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com