使用 python中 pandas 将 Excel 转换为 CSV 文件

[复制链接]
发表于 2026-1-3 22:56:46 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
在数据处理惩罚和分析中,我们经常必要将 Excel 文件转换为 CSV 格式。CSV 文件因其简朴、易于处理惩罚的特点,广泛用于数据互换。本文将先容怎样使用 wxPython 创建一个简朴的图形用户界面(GUI),团结 pandas 库,实现 Excel 文件到 CSV 文件的转换功能。
C:\pythoncode\new\excel2csv.py
全部代码
  1. import wx
  2. import pandas as pd
  3. import os
  4. class MyFrame(wx.Frame):
  5.     def __init__(self):
  6.         super().__init__(parent=None, title='Excel to CSV Converter')
  7.         panel = wx.Panel(self)
  8.         self.file_picker = wx.FilePickerCtrl(panel, message="Select an Excel file", wildcard="Excel files (*.xlsx)|*.xlsx")
  9.         self.line_count_label = wx.StaticText(panel, label='Number of rows to convert:')
  10.         self.line_count_text = wx.TextCtrl(panel, value='0')
  11.         self.convert_button = wx.Button(panel, label='Convert to CSV')
  12.         self.convert_button.Bind(wx.EVT_BUTTON, self.on_convert)
  13.         sizer = wx.BoxSizer(wx.VERTICAL)
  14.         sizer.Add(self.file_picker, 0, wx.ALL | wx.EXPAND, 5)
  15.         sizer.Add(self.line_count_label, 0, wx.ALL | wx.EXPAND, 5)
  16.         sizer.Add(self.line_count_text, 0, wx.ALL | wx.EXPAND, 5)
  17.         sizer.Add(self.convert_button, 0, wx.ALL | wx.CENTER, 5)
  18.         panel.SetSizer(sizer)
  19.         self.Show()
  20.     def on_convert(self, event):
  21.         xlsx_path = self.file_picker.GetPath()
  22.         if not xlsx_path:
  23.             wx.MessageBox("Please select an Excel file.", "Error", wx.OK | wx.ICON_ERROR)
  24.             return
  25.         # 获取用户输入的行数
  26.         try:
  27.             row_count = int(self.line_count_text.GetValue())
  28.         except ValueError:
  29.             wx.MessageBox("Please enter a valid number.", "Error", wx.OK | wx.ICON_ERROR)
  30.             return
  31.         # 确定输出的CSV文件路径
  32.         csv_path = os.path.splitext(xlsx_path)[0] + '.csv'
  33.         try:
  34.             # 读取Excel文件并转换为CSV,限制转换的行数
  35.             df = pd.read_excel(xlsx_path)
  36.             if row_count > 0:
  37.                 df = df.head(row_count)  # 只选择前 row_count 行
  38.             df.to_csv(csv_path, index=False)
  39.             wx.MessageBox(f"Converted to {csv_path}", "Success", wx.OK | wx.ICON_INFORMATION)
  40.         except Exception as e:
  41.             wx.MessageBox(f"Failed to convert: {str(e)}", "Error", wx.OK | wx.ICON_ERROR)
  42. if __name__ == '__main__':
  43.     app = wx.App(False)
  44.     frame = MyFrame()
  45.     app.MainLoop()
复制代码
情况预备

在开始之前,请确保你已安装以下库:
  1. pip install wxPython pandas openpyxl
复制代码

  • wxPython 用于创建 GUI。
  • pandas 用于处理惩罚 Excel 和 CSV 文件。
  • openpyxl 是 pandas 处理惩罚 Excel 文件的依靠。
创建 wxPython 应用步伐

我们将创建一个简朴的应用步伐,允许用户选择一个 Excel 文件,并输入想要转换的行数。以下是完备的代码示例:
  1. import wx
  2. import pandas as pd
  3. import os
  4. class MyFrame(wx.Frame):
  5.     def __init__(self):
  6.         super().__init__(parent=None, title='Excel to CSV Converter')
  7.         panel = wx.Panel(self)
  8.         self.file_picker = wx.FilePickerCtrl(panel, message="Select an Excel file", wildcard="Excel files (*.xlsx)|*.xlsx")
  9.         self.line_count_label = wx.StaticText(panel, label='Number of rows to convert:')
  10.         self.line_count_text = wx.TextCtrl(panel, value='0')
  11.         self.convert_button = wx.Button(panel, label='Convert to CSV')
  12.         self.convert_button.Bind(wx.EVT_BUTTON, self.on_convert)
  13.         sizer = wx.BoxSizer(wx.VERTICAL)
  14.         sizer.Add(self.file_picker, 0, wx.ALL | wx.EXPAND, 5)
  15.         sizer.Add(self.line_count_label, 0, wx.ALL | wx.EXPAND, 5)
  16.         sizer.Add(self.line_count_text, 0, wx.ALL | wx.EXPAND, 5)
  17.         sizer.Add(self.convert_button, 0, wx.ALL | wx.CENTER, 5)
  18.         panel.SetSizer(sizer)
  19.         self.Show()
  20.     def on_convert(self, event):
  21.         xlsx_path = self.file_picker.GetPath()
  22.         if not xlsx_path:
  23.             wx.MessageBox("Please select an Excel file.", "Error", wx.OK | wx.ICON_ERROR)
  24.             return
  25.         # 获取用户输入的行数
  26.         try:
  27.             row_count = int(self.line_count_text.GetValue())
  28.         except ValueError:
  29.             wx.MessageBox("Please enter a valid number.", "Error", wx.OK | wx.ICON_ERROR)
  30.             return
  31.         # 确定输出的CSV文件路径
  32.         csv_path = os.path.splitext(xlsx_path)[0] + '.csv'
  33.         try:
  34.             # 读取Excel文件并转换为CSV,限制转换的行数
  35.             df = pd.read_excel(xlsx_path)
  36.             if row_count > 0:
  37.                 df = df.head(row_count)  # 只选择前 row_count 行
  38.             df.to_csv(csv_path, index=False)
  39.             wx.MessageBox(f"Converted to {csv_path}", "Success", wx.OK | wx.ICON_INFORMATION)
  40.         except Exception as e:
  41.             wx.MessageBox(f"Failed to convert: {str(e)}", "Error", wx.OK | wx.ICON_ERROR)
  42. if __name__ == '__main__':
  43.     app = wx.App(False)
  44.     frame = MyFrame()
  45.     app.MainLoop()
复制代码
代码分析


  • 创建主窗口:我们通过继续 wx.Frame 创建了一个根本窗口,并在此中添加了文件选择器和输入框。
  • 文件选择器:使用 wx.FilePickerCtrl 让用户选择 Excel 文件。
  • 行数输入:用户可以输入渴望转换的行数。我们使用 wx.TextCtrl 来获取这个值。
  • 转换逻辑:当用户点击转换按钮时,步伐会读取 Excel 文件并提取指定行数的数据,然后将其生存为 CSV 文件。
  • 错误处理惩罚:使用 try-except 块来处理惩罚大概出现的错误,并使用 wx.MessageBox 提供反馈。
怎样运行

将上述代码生存为 Python 文件(如 excel_to_csv.py),并在下令行中运行:
  1. python excel_to_csv.py
复制代码
运行后,将出现一个窗口,您可以选择一个 Excel 文件,输入想要转换的行数,然后点击转换按钮。步伐将天生一个同名的 CSV 文件。
运行结果


总结

通过这篇文章,我们实现了一个简朴的图形用户界面应用步伐,允许用户方便地将 Excel 文件转换为 CSV 格式。这个应用步伐展示了 wxPython 和 pandas 的强盛功能,是数据处理惩罚工具箱中的一个有用工具。
渴望这个项目可以或许资助你更好地明白数据转换的过程,并鼓励你举行更多的编程实践!
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表