Converting an Excel file into a JSON file is a common task that Python developers handle. It allows us to transition data from Excel, which is a tabular form, to JSON, a nested and more flexible structure.
This conversion usually happens when we want to expose our Excel data to an API or web service in the form of a JSON. In this tutorial, we will guide you through the process of converting an Excel file into a JSON file using Python.
Step 1: Create an Excel file
First, you need to create a file. It can look like this:
Step 2: Install Required Libraries
Firstly, we need to install two Python libraries: pandas and xlrd. Pandas is a powerful Python library that provides essential data structures like dataframes for data analysis. xlrd is a library to read data and format information from Excel files.
You can install both libraries using pip, which is a package management system used to install and manage software packages written in Python.
1 |
pip install pandas xlrd |
Step 3: Prepare Your Excel File
For this tutorial, we will use an example Excel file named ‘sample.xlsx’. Make sure your Excel file has headers for each column, which will be essential while converting it to a JSON file. Have your Excel file ready in the same folder where you’ll run your Python script.
Step 4: Write the Python Code
Let’s write a Python code using pandas to read the Excel file and convert it into JSON:
1 2 3 4 5 6 7 |
import pandas as pd # Load the Excel file df = pd.read_excel('sample.xlsx') # Convert the Excel file to Json df.to_json('sample.json') |
Step 5: Run the Python Code
Now, you can run the Python script. If every step was followed correctly, you would get a JSON file named ‘sample.json’ in the same directory.
{ "Name": { "0": "Alice", "1": "Bob", "2": "Charlie" }, "Age": { "0": 30, "1": 25, "2": 35 }, "Occupation": { "0": "Software Engineer", "1": "Data Analyst", "2": "IT Manager" } }
Conclusion
In this tutorial, we went over how to convert an Excel file to a JSON file using Python. Python with the pandas and xlrd libraries makes the task incredibly straightforward. Now, you are ready to transform your Excel sheets into JSON format and utilize them as per your project needs. Happy coding!