5 Best Ways to Create a GUI to Convert CSV Files to Excel Using Python

πŸ’‘ Problem Formulation: Converting CSV files to Excel format is a common task that may need to be performed by less technical individuals. The input will be a .csv file containing structured data, and the desired output is an .xlsx file with the same data structured in tabular form as an Excel spreadsheet. A GUI makes the conversion process user-friendly, especially for non-programmers.

Method 1: Using Tkinter and Pandas

This method involves the use of Python’s built-in Tkinter library for GUI development and the popular Pandas library for data manipulation. Tkinter provides the graphical interface allowing users to select the CSV file, which is then converted to Excel format using Pandas’ powerful data handling capabilities. It is self-contained and fairly straightforward to implement.

Here’s an example:

import tkinter as tk
from tkinter import filedialog
import pandas as pd

def convert_csv_to_excel():
    csv_file_path = filedialog.askopenfilename()
    if csv_file_path.endswith('.csv'):
        df = pd.read_csv(csv_file_path)
        excel_path = csv_file_path.replace('.csv', '.xlsx')
        df.to_excel(excel_path, index=False)
        print(f'Converted {csv_file_path} to {excel_path}')

root = tk.Tk()
convert_button = tk.Button(root, text="Convert CSV to Excel", command=convert_csv_to_excel)
convert_button.pack()
root.mainloop()

Output:

Converted ./data/sample.csv to ./data/sample.xlsx

The code snippet creates a basic window with a button that, when clicked, opens a file dialogue to select a .csv file. The file is read into a Pandas DataFrame, then saved as an Excel file with the same name in the same directory. The GUI is very minimalistic, making the process user-friendly and straightforward.

Method 2: Using PySimpleGUI and XlsxWriter

PySimpleGUI is a wrapper for Tkinter that simplifies GUI creation, while XlsxWriter is a Python library used to write files in the Excel 2007+ XLSX format. Using PySimpleGUI allows for writing more readable and concise code for the GUI, and XlsxWriter provides extensive options for formatting the Excel output.

Here’s an example:

import PySimpleGUI as sg
import pandas as pd

layout = [
    [sg.Text('CSV file to Convert')],
    [sg.Input(), sg.FileBrowse()],
    [sg.Button('Convert'), sg.Button('Exit')]
]

window = sg.Window('CSV to Excel Converter', layout)

while True:
    event, values = window.read()
    if event in (None, 'Exit'):
        break
    if event == 'Convert':
        csv_file = values[0]
        if csv_file.endswith('.csv'):
            df = pd.read_csv(csv_file)
            excel_file = csv_file.replace('.csv', '.xlsx')
            df.to_excel(excel_file, engine='xlsxwriter', index=False)
            sg.Popup('Conversion Completed!', f'The file was saved as {excel_file}')
window.close()

Output:

A popup window appears with the message “Conversion Completed! The file was saved as ./data/sample.xlsx”

The above code constructs a simple PySimpleGUI window with file browsing and convert functionalities. Upon clicking ‘Convert’, the selected CSV file is processed by Pandas and written as an Excel file using XlsxWriter. The output is signaled to the user via a popup message, indicating successful conversion and the file’s location.

Method 3: Using PyQt5 and Openpyxl

PyQt5 is a set of Python bindings for Qt application framework, allowing the creation of complex and attractive GUIs. Openpyxl is a Python library for reading and writing Excel 2010 xlsx/xlsm files. This method provides a more advanced GUI experience and additional functionality for working with Excel files.

Here’s an example:

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout, QFileDialog
import pandas as pd

class CSVToExcelConverter(QWidget):
    def __init__(self):
        super().__init__()
        self.init_ui()

    def init_ui(self):
        self.setWindowTitle('CSV to Excel')
        layout = QVBoxLayout()
        self.convert_button = QPushButton('Convert CSV to Excel')
        self.convert_button.clicked.connect(self.convert_csv)
        layout.addWidget(self.convert_button)
        self.setLayout(layout)

    def convert_csv(self):
        csv_file, _ = QFileDialog.getOpenFileName(self, 'Open CSV file', '', 'CSV files (*.csv)')
        if csv_file:
            df = pd.read_csv(csv_file)
            excel_path = csv_file.replace('.csv', '.xlsx')
            df.to_excel(excel_path, index=False)
            print(f'Converted {csv_file} to {excel_path}')
            
app = QApplication(sys.argv)
converter = CSVToExcelConverter()
converter.show()
sys.exit(app.exec_())

Output:

Converted /path/to/sample.csv to /path/to/sample.xlsx

This script uses PyQt5 to build a more feature-rich application than those possible with Tkinter or PySimpleGUI. Users can convert selected CSV files to Excel, with the operation being managed through Pandas. Openpyxl is utilized behind the scenes by Pandas to write the Excel file.

Method 4: Using wxPython and Pandas

wxPython is another library for creating native GUIs in Python. In combination with Pandas, one can craft a cross-platform application to convert CSV files to Excel. wxPython allows extensive customization of the GUI and provides native look-and-feel on different operating systems.

Here’s an example:

import wx
import pandas as pd

class CSVFrame(wx.Frame):
    def __init__(self):
        super().__init__(parent=None, title='Convert CSV to Excel')
        panel = wx.Panel(self)
        my_sizer = wx.BoxSizer(wx.VERTICAL)
        
        self.text_ctrl = wx.TextCtrl(panel)
        my_sizer.Add(self.text_ctrl, 0, wx.ALL | wx.EXPAND, 5)
        
        my_btn = wx.Button(panel, label='Convert')
        my_btn.Bind(wx.EVT_BUTTON, self.on_convert)
        my_sizer.Add(my_btn, 0, wx.ALL | wx.CENTER, 5)
        
        panel.SetSizer(my_sizer)
        self.Show()

    def on_convert(self, event):
        csv_file = self.text_ctrl.GetValue()
        if csv_file.endswith('.csv'):
            df = pd.read_csv(csv_file)
            excel_file = csv_file.replace('.csv', '.xlsx')
            df.to_excel(excel_file, index=False)
            dlg = wx.MessageDialog(None, f'Converted {csv_file} to {excel_file}.', 'Conversion Complete', wx.OK)
            dlg.ShowModal()
            dlg.Destroy()

if __name__ == '__main__':
    app = wx.App(False)
    frame = CSVFrame()
    app.MainLoop()

Output:

A dialog box stating “Converted /path/to/sample.csv to /path/to/sample.xlsx.”

This example code snippet creates a wxPython application window where a user can enter the path to a CSV file, and upon clicking ‘Convert’, Pandas reads the CSV file and writes an Excel file. A dialog box then confirms the completion of the conversion.

Bonus One-Liner Method 5: Using the Command Line

For those preferring not to implement a full GUI or wishing for a quick conversion, Python’s command-line capabilities can come in handy. Below is a one-liner that handles the conversion with minimal user input.

Here’s an example:

python -c "import pandas as pd; df=pd.read_csv('input.csv'); df.to_excel('output.xlsx', index=False)"

Output:

There is no explicit output, but the input.csv file is converted and saved as output.xlsx

The provided command can be run directly in the terminal. It leverages Python’s ability to execute inline commands and uses Pandas to convert ‘input.csv’ to ‘output.xlsx’. There is no GUI, and the file paths are hard-coded in this one-liner, which may not be ideal for all use cases.

Summary/Discussion

  • Method 1: Tkinter and Pandas. Strengths: Uses only built-in and well-supported libraries. Weaknesses: The GUI is basic and not as modern looking.
  • Method 2: PySimpleGUI and XlsxWriter. Strengths: Simplified code and the ability to format Excel files extensively. Weaknesses: Not as advanced in terms of GUI capabilities as PyQt5 or wxPython.
  • Method 3: PyQt5 and Openpyxl. Strengths: Offers a rich set of features and a professional look. Weaknesses: Steeper learning curve compared to Tkinter or PySimpleGUI.
  • Method 4: wxPython and Pandas. Strengths: Cross-platform with a native look-and-feel. Weaknesses: Less straightforward to set up and distribute than simpler GUI frameworks.
  • Method 5: Command Line. Strengths: Quick and easy with no need for GUI setup. Weaknesses: Not user-friendly for non-technical individuals and lacks flexibility in file selection.