马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
在数据处理惩罚和分析中,我们经常必要将 Excel 文件转换为 CSV 格式。CSV 文件因其简朴、易于处理惩罚的特点,广泛用于数据互换。本文将先容怎样使用 wxPython 创建一个简朴的图形用户界面(GUI),团结 pandas 库,实现 Excel 文件到 CSV 文件的转换功能。
C:\pythoncode\new\excel2csv.py
全部代码
- import wx
- import pandas as pd
- import os
- class MyFrame(wx.Frame):
- def __init__(self):
- super().__init__(parent=None, title='Excel to CSV Converter')
- panel = wx.Panel(self)
- self.file_picker = wx.FilePickerCtrl(panel, message="Select an Excel file", wildcard="Excel files (*.xlsx)|*.xlsx")
- self.line_count_label = wx.StaticText(panel, label='Number of rows to convert:')
- self.line_count_text = wx.TextCtrl(panel, value='0')
- self.convert_button = wx.Button(panel, label='Convert to CSV')
- self.convert_button.Bind(wx.EVT_BUTTON, self.on_convert)
- sizer = wx.BoxSizer(wx.VERTICAL)
- sizer.Add(self.file_picker, 0, wx.ALL | wx.EXPAND, 5)
- sizer.Add(self.line_count_label, 0, wx.ALL | wx.EXPAND, 5)
- sizer.Add(self.line_count_text, 0, wx.ALL | wx.EXPAND, 5)
- sizer.Add(self.convert_button, 0, wx.ALL | wx.CENTER, 5)
- panel.SetSizer(sizer)
- self.Show()
- def on_convert(self, event):
- xlsx_path = self.file_picker.GetPath()
- if not xlsx_path:
- wx.MessageBox("Please select an Excel file.", "Error", wx.OK | wx.ICON_ERROR)
- return
- # 获取用户输入的行数
- try:
- row_count = int(self.line_count_text.GetValue())
- except ValueError:
- wx.MessageBox("Please enter a valid number.", "Error", wx.OK | wx.ICON_ERROR)
- return
- # 确定输出的CSV文件路径
- csv_path = os.path.splitext(xlsx_path)[0] + '.csv'
- try:
- # 读取Excel文件并转换为CSV,限制转换的行数
- df = pd.read_excel(xlsx_path)
- if row_count > 0:
- df = df.head(row_count) # 只选择前 row_count 行
- df.to_csv(csv_path, index=False)
- wx.MessageBox(f"Converted to {csv_path}", "Success", wx.OK | wx.ICON_INFORMATION)
- except Exception as e:
- wx.MessageBox(f"Failed to convert: {str(e)}", "Error", wx.OK | wx.ICON_ERROR)
- if __name__ == '__main__':
- app = wx.App(False)
- frame = MyFrame()
- app.MainLoop()
复制代码 情况预备
在开始之前,请确保你已安装以下库:- pip install wxPython pandas openpyxl
复制代码
- wxPython 用于创建 GUI。
- pandas 用于处理惩罚 Excel 和 CSV 文件。
- openpyxl 是 pandas 处理惩罚 Excel 文件的依靠。
创建 wxPython 应用步伐
我们将创建一个简朴的应用步伐,允许用户选择一个 Excel 文件,并输入想要转换的行数。以下是完备的代码示例:- import wx
- import pandas as pd
- import os
- class MyFrame(wx.Frame):
- def __init__(self):
- super().__init__(parent=None, title='Excel to CSV Converter')
- panel = wx.Panel(self)
- self.file_picker = wx.FilePickerCtrl(panel, message="Select an Excel file", wildcard="Excel files (*.xlsx)|*.xlsx")
- self.line_count_label = wx.StaticText(panel, label='Number of rows to convert:')
- self.line_count_text = wx.TextCtrl(panel, value='0')
- self.convert_button = wx.Button(panel, label='Convert to CSV')
- self.convert_button.Bind(wx.EVT_BUTTON, self.on_convert)
- sizer = wx.BoxSizer(wx.VERTICAL)
- sizer.Add(self.file_picker, 0, wx.ALL | wx.EXPAND, 5)
- sizer.Add(self.line_count_label, 0, wx.ALL | wx.EXPAND, 5)
- sizer.Add(self.line_count_text, 0, wx.ALL | wx.EXPAND, 5)
- sizer.Add(self.convert_button, 0, wx.ALL | wx.CENTER, 5)
- panel.SetSizer(sizer)
- self.Show()
- def on_convert(self, event):
- xlsx_path = self.file_picker.GetPath()
- if not xlsx_path:
- wx.MessageBox("Please select an Excel file.", "Error", wx.OK | wx.ICON_ERROR)
- return
- # 获取用户输入的行数
- try:
- row_count = int(self.line_count_text.GetValue())
- except ValueError:
- wx.MessageBox("Please enter a valid number.", "Error", wx.OK | wx.ICON_ERROR)
- return
- # 确定输出的CSV文件路径
- csv_path = os.path.splitext(xlsx_path)[0] + '.csv'
- try:
- # 读取Excel文件并转换为CSV,限制转换的行数
- df = pd.read_excel(xlsx_path)
- if row_count > 0:
- df = df.head(row_count) # 只选择前 row_count 行
- df.to_csv(csv_path, index=False)
- wx.MessageBox(f"Converted to {csv_path}", "Success", wx.OK | wx.ICON_INFORMATION)
- except Exception as e:
- wx.MessageBox(f"Failed to convert: {str(e)}", "Error", wx.OK | wx.ICON_ERROR)
- if __name__ == '__main__':
- app = wx.App(False)
- frame = MyFrame()
- app.MainLoop()
复制代码 代码分析
- 创建主窗口:我们通过继续 wx.Frame 创建了一个根本窗口,并在此中添加了文件选择器和输入框。
- 文件选择器:使用 wx.FilePickerCtrl 让用户选择 Excel 文件。
- 行数输入:用户可以输入渴望转换的行数。我们使用 wx.TextCtrl 来获取这个值。
- 转换逻辑:当用户点击转换按钮时,步伐会读取 Excel 文件并提取指定行数的数据,然后将其生存为 CSV 文件。
- 错误处理惩罚:使用 try-except 块来处理惩罚大概出现的错误,并使用 wx.MessageBox 提供反馈。
怎样运行
将上述代码生存为 Python 文件(如 excel_to_csv.py),并在下令行中运行:运行后,将出现一个窗口,您可以选择一个 Excel 文件,输入想要转换的行数,然后点击转换按钮。步伐将天生一个同名的 CSV 文件。
运行结果
总结
通过这篇文章,我们实现了一个简朴的图形用户界面应用步伐,允许用户方便地将 Excel 文件转换为 CSV 格式。这个应用步伐展示了 wxPython 和 pandas 的强盛功能,是数据处理惩罚工具箱中的一个有用工具。
渴望这个项目可以或许资助你更好地明白数据转换的过程,并鼓励你举行更多的编程实践!
|