Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Create a GUI to convert CSV file to Excel file using Python
As businesses grow and expand, they need to manage a lot of information. This information may come in different formats, and being able to convert them to the right format is important for the smooth running of business operations. One of the ways to handle this is by converting CSV files to Excel format. In this tutorial, we will build a Graphical User Interface (GUI) in Python to convert CSV files to Excel files.
What is a CSV File?
A CSV (Comma Separated Values) file is a plain text file that stores tabular data in a structured format. Each line in a CSV file represents a record, and each record contains one or more fields separated by commas. CSV files are widely used in data science, machine learning, and other fields where tabular data needs to be processed or analyzed.
The key advantages of using CSV files in Python are:
Easy to Read and Write Python provides a built-in module called csv that makes it easy to read and write CSV files.
Lightweight and Efficient CSV files are lightweight and take up minimal disk space, making them ideal for storing large amounts of data.
Compatible with Other Programs CSV files are widely supported by many different programs and tools.
Advantages of Using Excel
Excel provides several advantages over CSV format:
Data Organization Excel allows you to organize data in multiple sheets with advanced formatting options.
Calculation Excel has powerful calculation capabilities with formulas, functions, and pivot tables.
Visualization Excel allows you to create charts and graphs to visualize your data effectively.
Prerequisites
Before creating the GUI, ensure you have:
-
Python 3.x installed
-
Required libraries:
pip install pandas openpyxl -
Basic understanding of Python and Tkinter
-
Any Python IDE or text editor
Building the CSV to Excel Converter
Step 1: Import Required Modules
import tkinter as tk from tkinter import filedialog, messagebox import pandas as pd import os
Step 2: Create the Conversion Function
def csv_to_excel():
try:
# Get input CSV file path
input_file_path = filedialog.askopenfilename(
title="Select CSV File",
filetypes=[("CSV files", "*.csv"), ("All files", "*.*")]
)
if not input_file_path:
return
# Read CSV file
df = pd.read_csv(input_file_path)
# Get output file path
output_file_name = os.path.basename(input_file_path).replace('.csv', '.xlsx')
output_file_path = filedialog.asksaveasfilename(
title="Save Excel File As",
defaultextension=".xlsx",
initialfile=output_file_name,
filetypes=[("Excel files", "*.xlsx"), ("All files", "*.*")]
)
if not output_file_path:
return
# Convert and save as Excel
df.to_excel(output_file_path, index=False)
messagebox.showinfo("Success", f"File converted successfully!\nSaved as: {output_file_path}")
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {str(e)}")
Step 3: Create the Main Window
# Create main window
root = tk.Tk()
root.title("CSV to Excel Converter")
root.geometry("400x250")
root.config(bg="#f0f0f0")
root.resizable(False, False)
# Add title label
title_label = tk.Label(
root,
text="CSV to Excel Converter",
font=("Arial", 16, "bold"),
bg="#f0f0f0",
fg="#333333"
)
title_label.pack(pady=20)
# Add instruction label
instruction_label = tk.Label(
root,
text="Click the button below to select a CSV file\nand convert it to Excel format",
font=("Arial", 10),
bg="#f0f0f0",
fg="#666666"
)
instruction_label.pack(pady=10)
# Add convert button
convert_button = tk.Button(
root,
text="Select CSV & Convert to Excel",
command=csv_to_excel,
font=("Arial", 12, "bold"),
bg="#4CAF50",
fg="white",
padx=20,
pady=10,
cursor="hand2"
)
convert_button.pack(pady=20)
# Add exit button
exit_button = tk.Button(
root,
text="Exit",
command=root.quit,
font=("Arial", 10),
bg="#f44336",
fg="white",
padx=15,
pady=5,
cursor="hand2"
)
exit_button.pack(pady=10)
Step 4: Run the Application
# Start the GUI
if __name__ == "__main__":
root.mainloop()
Complete Code
import tkinter as tk
from tkinter import filedialog, messagebox
import pandas as pd
import os
def csv_to_excel():
try:
# Get input CSV file path
input_file_path = filedialog.askopenfilename(
title="Select CSV File",
filetypes=[("CSV files", "*.csv"), ("All files", "*.*")]
)
if not input_file_path:
return
# Read CSV file
df = pd.read_csv(input_file_path)
# Get output file path
output_file_name = os.path.basename(input_file_path).replace('.csv', '.xlsx')
output_file_path = filedialog.asksaveasfilename(
title="Save Excel File As",
defaultextension=".xlsx",
initialfile=output_file_name,
filetypes=[("Excel files", "*.xlsx"), ("All files", "*.*")]
)
if not output_file_path:
return
# Convert and save as Excel
df.to_excel(output_file_path, index=False)
messagebox.showinfo("Success", f"File converted successfully!\nSaved as: {output_file_path}")
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {str(e)}")
# Create main window
root = tk.Tk()
root.title("CSV to Excel Converter")
root.geometry("400x250")
root.config(bg="#f0f0f0")
root.resizable(False, False)
# Add title label
title_label = tk.Label(
root,
text="CSV to Excel Converter",
font=("Arial", 16, "bold"),
bg="#f0f0f0",
fg="#333333"
)
title_label.pack(pady=20)
# Add instruction label
instruction_label = tk.Label(
root,
text="Click the button below to select a CSV file\nand convert it to Excel format",
font=("Arial", 10),
bg="#f0f0f0",
fg="#666666"
)
instruction_label.pack(pady=10)
# Add convert button
convert_button = tk.Button(
root,
text="Select CSV & Convert to Excel",
command=csv_to_excel,
font=("Arial", 12, "bold"),
bg="#4CAF50",
fg="white",
padx=20,
pady=10,
cursor="hand2"
)
convert_button.pack(pady=20)
# Add exit button
exit_button = tk.Button(
root,
text="Exit",
command=root.quit,
font=("Arial", 10),
bg="#f44336",
fg="white",
padx=15,
pady=5,
cursor="hand2"
)
exit_button.pack(pady=10)
# Start the GUI
if __name__ == "__main__":
root.mainloop()
How It Works
The application follows these steps:
-
User clicks the "Select CSV & Convert to Excel" button
-
A file dialog opens for CSV file selection
-
Pandas reads the CSV file into a DataFrame
-
Another dialog opens for saving the Excel file
-
The DataFrame is saved as an Excel file using
to_excel() -
A success message confirms the conversion
Key Features
-
User-friendly GUI with clear instructions
-
Error handling with informative messages
-
File type filtering in dialogs
-
Automatic filename suggestion for output
Limitations
-
Only converts one file at a time
-
Requires pandas and openpyxl libraries
-
No preview of data before conversion
Conclusion
This tutorial demonstrated how to create a user-friendly GUI application for converting CSV files to Excel format using Python's tkinter and pandas libraries. The application includes proper error handling and provides a clean interface for file conversion tasks.
