from
datetime
import
datetime
import
PySimpleGUI as sg
import
win32com.client as win32
import
os
import
sys
excel
=
win32.gencache.EnsureDispatch(
'Excel.Application'
)
def
convert_file(file_name, output_format):
input_ext
=
os.path.splitext(file_name)[
-
1
].lower()
if
input_ext
not
in
[
'.xlsx'
,
'.xls'
]:
return
f
'{file_name} 不支持的文件类型'
elif
input_ext
=
=
output_format:
return
f
'{file_name} 当前文件类型无需转换'
try
:
wb
=
excel.Workbooks.
Open
(file_name)
new_file_name
=
os.path.splitext(file_name)[
0
]
+
output_format
new_file_name
=
new_file_name.replace(
"/"
,
"\\"
)
wb.SaveAs(new_file_name, FileFormat
=
get_format(output_format))
wb.Close()
return
f
'转换成功:{file_name} 转换为 {output_format}'
except
Exception as e:
excel.Application.Quit()
return
f
'【转换失败】:{file_name}'
def
get_format(file_ext):
if
file_ext
=
=
'.xls'
:
return
56
elif
file_ext
=
=
'.xlsx'
:
return
51
def
gui():
sg.theme(
'DarkBlue'
)
icon_path
=
'./icon1.ico'
layout
=
[
[sg.Text(
'文件格式转换工具'
, font
=
(
'黑体'
,
32
), justification
=
'center'
, text_color
=
'#00CED1'
)],
[sg.Text(
'选择要转换的文件'
, font
=
(
'黑体'
,
16
), text_color
=
'#00CED1'
)],
[sg.
Input
(key
=
'文件路径'
, size
=
(
40
,
1
), font
=
(
'黑体'
,
12
)),
sg.FilesBrowse(
'选择'
, file_types
=
((
"Excel文件"
,
"*.xlsx; *.xls"
),), target
=
'文件路径'
,
font
=
(
'黑体'
,
12
), button_color
=
(
'white'
,
'#00CED1'
))],
[sg.Radio(
'xlsx转xls'
,
'选择转换格式'
, key
=
'xlsx_to_xls'
, default
=
True
, font
=
(
'黑体'
,
14
), enable_events
=
True
),
sg.Radio(
'xls转xlsx'
,
'选择转换格式'
, key
=
'xls_to_xlsx'
, font
=
(
'黑体'
,
14
), enable_events
=
True
)],
[sg.Button(
'转换'
, key
=
'转换'
, button_color
=
(
'white'
,
'#00CED1'
), size
=
(
10
,
1
), font
=
(
'黑体'
,
14
)),
sg.Button(
'清空'
, key
=
'清空'
, size
=
(
10
,
1
), font
=
(
'黑体'
,
14
))],
[sg.Output(size
=
(
60
,
10
), key
=
'sg_output'
, font
=
(
'黑体'
,
12
))]
]
window
=
sg.Window(
'文件格式转换工具.By.Eric.'
, layout, element_justification
=
'center'
, resizable
=
True
,
finalize
=
True
, icon
=
icon_path)
while
True
:
event, values
=
window.read()
if
event
=
=
sg.WIN_CLOSED:
excel.Application.Quit()
break
if
event
=
=
'转换'
:
output_format
=
'.xls'
if
values[
'xlsx_to_xls'
]
else
'.xlsx'
for
i
in
values[
'文件路径'
].split(
';'
):
print
(convert_file(i, output_format))
excel.Application.Quit()
window[
'文件路径'
].update('')
elif
event
=
=
'清空'
:
window[
'文件路径'
].update('')
window.FindElement(
'sg_output'
).Update("")
window.close()
if
__name__
=
=
'__main__'
:
gui()