python使用pandas實現(xiàn)Excel轉(zhuǎn)換為CSV文件
在數(shù)據(jù)處理和分析中,我們經(jīng)常需要將 Excel 文件轉(zhuǎn)換為 CSV 格式。CSV 文件因其簡單、易于處理的特點,廣泛用于數(shù)據(jù)交換。本文將介紹如何使用 wxPython 創(chuàng)建一個簡單的圖形用戶界面(GUI),結(jié)合 pandas 庫,實現(xiàn) Excel 文件到 CSV 文件的轉(zhuǎn)換功能。
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 # 獲取用戶輸入的行數(shù) 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文件并轉(zhuǎn)換為CSV,限制轉(zhuǎn)換的行數(shù) 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()
環(huán)境準(zhǔn)備
在開始之前,請確保你已安裝以下庫:
pip install wxPython pandas openpyxl
- wxPython 用于創(chuàng)建 GUI。
- pandas 用于處理 Excel 和 CSV 文件。
- openpyxl 是 pandas 處理 Excel 文件的依賴。
創(chuàng)建 wxPython 應(yīng)用程序
我們將創(chuàng)建一個簡單的應(yīng)用程序,允許用戶選擇一個 Excel 文件,并輸入想要轉(zhuǎn)換的行數(shù)。以下是完整的代碼示例:
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 # 獲取用戶輸入的行數(shù) 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文件并轉(zhuǎn)換為CSV,限制轉(zhuǎn)換的行數(shù) 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()
代碼解析
創(chuàng)建主窗口:我們通過繼承 wx.Frame 創(chuàng)建了一個基本窗口,并在其中添加了文件選擇器和輸入框。
文件選擇器:使用 wx.FilePickerCtrl 讓用戶選擇 Excel 文件。
行數(shù)輸入:用戶可以輸入希望轉(zhuǎn)換的行數(shù)。我們使用 wx.TextCtrl 來獲取這個值。
轉(zhuǎn)換邏輯:當(dāng)用戶點擊轉(zhuǎn)換按鈕時,程序會讀取 Excel 文件并提取指定行數(shù)的數(shù)據(jù),然后將其保存為 CSV 文件。
錯誤處理:使用 try-except 塊來處理可能出現(xiàn)的錯誤,并使用 wx.MessageBox 提供反饋。
如何運行
將上述代碼保存為 Python 文件(如 excel_to_csv.py),并在命令行中運行:
python excel_to_csv.py
運行后,將出現(xiàn)一個窗口,您可以選擇一個 Excel 文件,輸入想要轉(zhuǎn)換的行數(shù),然后點擊轉(zhuǎn)換按鈕。程序?qū)⑸梢粋€同名的 CSV 文件。
運行結(jié)果
總結(jié)
通過這篇文章,我們實現(xiàn)了一個簡單的圖形用戶界面應(yīng)用程序,允許用戶方便地將 Excel 文件轉(zhuǎn)換為 CSV 格式。這個應(yīng)用程序展示了 wxPython
和 pandas
的強大功能,是數(shù)據(jù)處理工具箱中的一個有用工具。
以上就是python使用pandas實現(xiàn)Excel轉(zhuǎn)換為CSV文件的詳細(xì)內(nèi)容,更多關(guān)于python pandas Excel轉(zhuǎn)CSV的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python使用itchat模塊實現(xiàn)群聊轉(zhuǎn)發(fā),自動回復(fù)功能示例
這篇文章主要介紹了Python使用itchat模塊實現(xiàn)群聊轉(zhuǎn)發(fā),自動回復(fù)功能,結(jié)合實例形式分析了Python基于itchat模塊針對微信信息的發(fā)送、回復(fù)等相關(guān)操作技巧,需要的朋友可以參考下2019-08-08Python實現(xiàn)簡單的HttpServer服務(wù)器示例
本篇文章主要介紹了Python實現(xiàn)簡單的HttpServer服務(wù)器示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-09-09python構(gòu)造icmp echo請求和實現(xiàn)網(wǎng)絡(luò)探測器功能代碼分享
本文分享了二個python示例,python構(gòu)造icmp echo請求、實現(xiàn)網(wǎng)絡(luò)探測器功能代碼,類似nmap功能2014-01-01