PySimpleGUI图形化界面实现Office文件格式转换
- Python实现三种文件两个版本的格式转换
- 1、doc与docx格式互相转换
- 2、xls与xlsx格式互相转换
- 3、ppt与pptx格式互相转换
- Python+PySimpleGUI实现综合版本
Python实现三种文件两个版本的格式转换
1、doc与docx格式互相转换
这里主要运用了Win32com来实现两种文件格式转换,后续也是一样的
# -*- coding:utf-8 -*-
# -*- Author:valecalida -*-
from os import path
from win32com import client
class DocWithDocx(object):
def __init__(self, filename, out_path):
self.filename = (str(filename).strip().replace("/", "\\"))
self.f_name = path.split(self.filename)[-1]
self.out_path = str(out_path).strip().replace("/", "\\") + "\\"
self.final_name = self.out_path + self.f_name
def doc2docx(self):
word = client.Dispatch('Word.Application')
word.DisplayAlerts = False
doc = word.Documents.Open(self.filename)
doc.SaveAs(self.final_name + "x", 12)
doc.Close()
word.Quit()
def docx2doc(self):
word = client.Dispatch('Word.Application')
word.DisplayAlerts = False
doc = word.Documents.Open(self.filename)
doc.SaveAs(self.final_name[:-1], 0)
doc.Close()
word.Quit()
2、xls与xlsx格式互相转换
# -*- coding:utf-8 -*-
# -*- Author:valecalida -*-
import win32com.client as win32
from os import path
class XLSWithXLSX(object):
def __init__(self, filename, out_path):
self.filename = (str(filename).strip().replace("/", "\\"))
self.f_name = path.split(self.filename)[-1]
self.out_path = str(out_path).strip().replace("/", "\\") + "\\"
self.final_name = self.out_path + self.f_name
def xls2xlsx(self):
excel = win32.gencache.EnsureDispatch('Excel.Application')
excel.DisplayAlerts = False
wb = excel.Workbooks.Open(fname)
wb.CheckCompatibility = False
wb.DoNotPromptForConvert = True
wb.SaveAs(self.final_name + "x", FileFormat=51) # FileFormat = 51 is for .xlsx extension
wb.Close() # FileFormat = 56 is for .xls extension
excel.Application.Quit()
def xlsx2xls(self):
excel = win32.gencache.EnsureDispatch('Excel.Application')
excel.DisplayAlerts = False
wb = excel.Workbooks.Open(fname)
wb.CheckCompatibility = False
wb.DoNotPromptForConvert = True
wb.SaveAs(self.final_name[:-1], FileFormat=56)
# FileFormat = 56 is for .xls extension
wb.Close()
excel.Application.Quit()
3、ppt与pptx格式互相转换
# -*- coding:utf-8 -*-
# -*- Author:valecalida -*-
import win32com.client
from os import path
class PPTWithPPTX(object):
def __init__(self, filename, out_path):
self.filename = (str(filename).strip().replace("/", "\\"))
self.f_name = path.split(self.filename)[-1]
self.out_path = str(out_path).strip().replace("/", "\\") + "\\"
self.final_name = self.out_path + self.f_name
def ppt2pptx(self):
ppt_app = win32com.client.Dispatch("Powerpoint.Application")
ppt_presentation = ppt_app.Presentations.Open(self.filename)
ppt_presentation.SaveAs(self.final_name + "x", FileFormat=24)
ppt_presentation.close()
ppt_app.Quit()
def pptx2ppt(self):
ppt_app = win32com.client.Dispatch("Powerpoint.Application")
ppt_presentation = ppt_app.Presentations.Open(self.filename)
ppt_presentation.SaveAs(self.final_name[:-1])
ppt_presentation.close()
ppt_app.Quit()
Python+PySimpleGUI实现综合版本
上面已经实现了每个文件格式的单独转换,现在只需要加上图形化界面就可以了,直接上代码
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# -*- Author:valecalida -*-
import win32com.client as win32
from os import path
import PySimpleGUI as sg
class OfficeFormatConversion(object):
def __init__(self, filename, out_path):
self.filename = (str(filename).strip().replace("/", "\\"))
self.f_name = path.split(self.filename)[-1]
self.out_path = str(out_path).strip().replace("/", "\\") + "\\"
self.final_name = self.out_path + self.f_name
def xls2xlsx(self):
excel = win32.gencache.EnsureDispatch('Excel.Application')
excel.DisplayAlerts = False
wb = excel.Workbooks.Open(self.filename)
wb.CheckCompatibility = False
wb.DoNotPromptForConvert = True
wb.SaveAs(self.final_name + "x", FileFormat=51) # FileFormat = 51 is for .xlsx extension
wb.Close() # FileFormat = 56 is for .xls extension
excel.Application.Quit()
def xlsx2xls(self):
excel = win32.gencache.EnsureDispatch('Excel.Application')
excel.DisplayAlerts = False
wb = excel.Workbooks.Open(self.filename)
wb.CheckCompatibility = False
wb.DoNotPromptForConvert = True
wb.SaveAs(self.final_name[:-1], FileFormat=56)
wb.Close()
excel.Application.Quit()
def ppt2pptx(self):
ppt_app = win32.Dispatch("Powerpoint.Application")
ppt_presentation = ppt_app.Presentations.Open(self.filename)
ppt_presentation.SaveAs(self.final_name + "x", FileFormat=24)
ppt_presentation.close()
ppt_app.Quit()
def pptx2ppt(self):
ppt_app = win32.Dispatch("Powerpoint.Application")
ppt_presentation = ppt_app.Presentations.Open(self.filename)
ppt_presentation.SaveAs(self.final_name[:-1])
ppt_presentation.close()
ppt_app.Quit()
def doc2docx(self):
word = win32.Dispatch('Word.Application')
word.DisplayAlerts = False
doc = word.Documents.Open(self.filename)
doc.SaveAs(self.final_name + "x", 12)
doc.Close()
word.Quit()
def docx2doc(self):
word = win32.Dispatch('Word.Application')
word.DisplayAlerts = False
doc = word.Documents.Open(self.filename)
doc.SaveAs(self.final_name[:-1], 0)
doc.Close()
word.Quit()
class OfficeFormatConversionGUI(object):
def __init__(self):
self.bgc = "#9C221D"
self.btc = "#9C221D on #FFF6F5"
self.FONT = ("微软雅黑", 16)
self.format_list = ["doc", "docx", "xls", "xlsx", "ppt", "pptx"]
self.layout = [
[sg.Text("请选择您要转换的Office文件: ", font=self.FONT, background_color=self.bgc)],
[
sg.Input("", key="_FILES_", font=self.FONT, size=(36, 1), text_color=self.bgc, disabled_readonly_background_color="#FFF6F5"),
sg.FilesBrowse("选择文件", font=self.FONT, size=(10, 1), button_color=self.btc)],
[
sg.Text("(非必选)把这些文件格式从: ", font=self.FONT, size=(20, 1), background_color=self.bgc),
sg.Combo(self.format_list, key="-DATA1-", font=self.FONT, size=(5, 6), default_value="请选择", enable_events=True, button_arrow_color=self.bgc, text_color=self.bgc,
background_color="#FFF6F5", button_background_color="#FFF6F5"),
sg.Text("转换为: ", font=self.FONT, background_color=self.bgc),
sg.Input("", key="-DATA2-", font=self.FONT, size=(4, 6), text_color=self.bgc, disabled_readonly_background_color="#FFF6F5"),
],
[sg.Text("转换后的文件将保存到:", font=self.FONT, background_color=self.bgc)],
[
sg.Input("", key="-FOLDER-", font=self.FONT, size=(36, 1)),
sg.FolderBrowse("选择文件夹", font=self.FONT, size=(10, 1), button_color=self.btc)
],
[sg.Text("",background_color=self.bgc)],
[
sg.Button("点我自动处理", key="-AUTO-", font=self.FONT, size=(10, 1), button_color=self.btc),
sg.Button("点我开始转换", key="-SUBMIT-", font=self.FONT, size=(10, 1), button_color=self.btc),
sg.Button("点我返回主页", key="-MAIN-", font=self.FONT, size=(10, 1), button_color=self.btc),
sg.Button("点我显示帮助", key="-HELP-", font=self.FONT, size=(10, 1), button_color=self.btc)
],
[
sg.Output(size=(80, 8), sbar_background_color="#9C221D", text_color="#9C221D",
sbar_frame_color="#9C221D", sbar_trough_color="#FFF6F5", background_color="#FFF6F5")
]
]
self.window = sg.Window(title="Office格式转换", layout=self.layout, background_color=self.bgc, finalize=True)
def run(self):
while True:
event, values = self.window.Read()
# print(event, values)
if event == "-DATA1-":
if values["-DATA1-"] == "docx":
self.window.Element("-DATA2-").Update("doc")
elif values["-DATA1-"] == "doc":
self.window.Element("-DATA2-").Update("docx")
elif values["-DATA1-"] == "xls":
self.window.Element("-DATA2-").Update("xlsx")
elif values["-DATA1-"] == "xlsx":
self.window.Element("-DATA2-").Update("xls")
elif values["-DATA1-"] == "ppt":
self.window.Element("-DATA2-").Update("pptx")
elif values["-DATA1-"] == "pptx":
self.window.Element("-DATA2-").Update("ppt")
elif event == "-SUBMIT-":
files = (str(values["_FILES_"]).strip()).split(";")
try:
files.remove("")
except ValueError:
pass
data = str(values["-DATA1-"]).strip()
out_path = str(values["-FOLDER-"]).strip()
# print(files, data, out_path)
# print(event, values)
if len(files) >= 1:
if data != "请选择":
if out_path:
for file in files:
try:
if data == "doc":
OfficeFormatConversion(file, out_path).doc2docx()
elif data == "docx":
OfficeFormatConversion(file, out_path).docx2doc()
elif data == "xls":
OfficeFormatConversion(file, out_path).xls2xlsx()
elif data == "xlsx":
OfficeFormatConversion(file, out_path).xlsx2xls()
elif data == "ppt":
OfficeFormatConversion(file, out_path).ppt2pptx()
elif data == "pptx":
OfficeFormatConversion(file, out_path).pptx2ppt()
print(f"[+] {path.split(file)[-1]} 已转换成功")
except FileNotFoundError:
print("[-] 看起来在有些文件在转换之前被移动了,请核实")
except PermissionError:
print("[-] 请查看您选择保存的文件夹是否允许写入文件")
else:
print("[-] 您尚未选择将转换后的文件保存到哪")
else:
print("[-] 您尚未选择要进行格式转换的文件格式")
else:
print("[-] 您尚未选择要进行格式转换的文件")
elif event == "-HELP-":
evo, _ = sg.Window("Office批量格式转换——操作帮助提示",
[
[sg.Multiline(
"""
1
2
3
4
5
6
7
""",
size=(56, 6))],
[sg.Button("我已知晓", size=(8, 1)), sg.Button("退出程序", size=(8, 1))]
], element_justification="center", font=("微软雅黑", 13, "bold"), ).read(close=True)
if evo == "我已知晓":
continue
elif evo == sg.WIN_CLOSED or evo == "Exit" or evo is None:
continue
else:
exit()
elif event == "-AUTO-":
files = (str(values["_FILES_"]).strip()).split(";")
try:
files.remove("")
except ValueError:
pass
out_path = str(values["-FOLDER-"]).strip()
if len(files) >= 1:
if out_path:
for file in files:
try:
if file.endswith("doc"):
print(f"[~] 识别到{path.split(file)[-1]} 为 doc 文件,开始转换")
OfficeFormatConversion(file, out_path).doc2docx()
print(f"[+] {path.split(file)[-1]} 已转换成功 docx 格式")
elif file.endswith("docx"):
print(f"[~] 识别到{path.split(file)[-1]} 为 docx 文件,开始转换")
OfficeFormatConversion(file, out_path).docx2doc()
print(f"[+] {path.split(file)[-1]} 已转换成功 doc 格式")
elif file.endswith("xls"):
print(f"[~] 识别到{path.split(file)[-1]} 为 xls 文件,开始转换")
OfficeFormatConversion(file, out_path).xls2xlsx()
print(f"[+] {path.split(file)[-1]} 已转换成功 xlsx 格式")
elif file.endswith("xlsx"):
print(f"[~] 识别到{path.split(file)[-1]} 为 xlsx 文件,开始转换")
OfficeFormatConversion(file, out_path).xlsx2xls()
print(f"[+] {path.split(file)[-1]} 已转换成功 xls 格式")
elif file.endswith("ppt"):
print(f"[~] 识别到{path.split(file)[-1]} 为 ppt 文件,开始转换")
OfficeFormatConversion(file, out_path).ppt2pptx()
print(f"[+] {path.split(file)[-1]} 已转换成功 pptx 格式")
elif file.endswith("pptx"):
print(f"[~] 识别到{path.split(file)[-1]} 为 pptx 文件,开始转换")
OfficeFormatConversion(file, out_path).pptx2ppt()
print(f"[+] {path.split(file)[-1]} 已转换成功 ppt 格式")
except FileNotFoundError:
print("[-] 看起来在有些文件在转换之前被移动了,请核实")
except PermissionError:
print("[-] 请查看您选择保存的文件夹是否允许写入文件")
else:
print("[-] 您尚未选择将转换后的文件保存到哪")
else:
print("[-] 您尚未选择要进行格式转换的文件")
elif event == sg.WIN_CLOSED or event == "Exit" or event is None:
exit()
OfficeFormatConversionGUI().run()
本人的代码能力有限,仅供各位看官娱乐,最终运行效果为:
如对程序有建议可直接评论或私聊~