用py 的PySimpleGUI 做一个可视化窗口,选择电脑中的文件,然后点击切换格式按钮可以将csv格式转换成xlsx
时间: 2024-03-27 07:41:02 浏览: 15
好的,以下是一个简单的示例代码,使用 PySimpleGUI 实现窗口可视化和文件选择,同时使用 pandas 库将 csv 格式转换为 xlsx 格式:
```python
import PySimpleGUI as sg
import pandas as pd
sg.theme('Default1')
layout = [
[sg.Text('选择需要转换的 CSV 文件')],
[sg.Input(key='input_file'), sg.FileBrowse(file_types=(('CSV 文件', '*.csv'),))],
[sg.Button('切换格式')],
[sg.Output(size=(60, 10))]
]
window = sg.Window('CSV 转 XLSX', layout)
while True:
event, values = window.read()
if event == sg.WIN_CLOSED:
break
if event == '切换格式':
input_file = values['input_file']
if not input_file.endswith('.csv'):
print('请选择 CSV 格式的文件!')
continue
output_file = input_file[:-4] + '.xlsx'
try:
df = pd.read_csv(input_file)
df.to_excel(output_file, index=False)
print(f'{input_file} 转换成功,保存为 {output_file}')
except Exception as e:
print(f'转换失败: {e}')
window.close()
```
运行程序后,可以选择需要转换的 CSV 文件,然后点击切换格式按钮进行转换。转换成功后,会在同一目录下生成同名的 xlsx 文件。