Convert JSON to/from Excel in Python – Full Guide with Examples

Convert JSON and Excel in Python using Spire.XLS – tutorial cover image

In many Python projects, especially those that involve APIs, data analysis, or business reporting, developers often need to convert Excel to JSON or JSON to Excel using Python code. These formats serve different but complementary roles: JSON is ideal for structured data exchange and storage, while Excel is widely used for sharing, editing, and presenting data in business environments.

This tutorial provides a complete, developer-focused guide to converting between JSON and Excel in Python. You'll learn how to handle nested data, apply Excel formatting, and resolve common conversion or encoding issues. We’ll use Python’s built-in json module to handle JSON data, and Spire.XLS for Python to read and write Excel files in .xlsx, .xls, and .csv formats — all without requiring Microsoft Excel or other third-party software.

Topics covered include:


Install Spire.XLS for Python

This library is used in this tutorial to generate and parse Excel files (.xlsx, .xls, .csv) as part of the JSON–Excel conversion workflow.

To get started, install the Spire.XLS for Python package from PyPI:

pip install spire.xls

You can also choose Free Spire.XLS for Python in smaller projects:

pip install spire.xls.free

Spire.XLS for Python runs on Windows, Linux, and macOS. It does not require Microsoft Excel or any COM components to be installed.

Why Choose Spire.XLS over Open-Source Libraries?

Many open-source Python libraries are great for general Excel tasks like simple data export or basic formatting. If your use case only needs straightforward table output, these tools often get the job done quickly.

However, when your project requires rich Excel formatting, multi-sheet reports, or an independent solution without Microsoft Office, Spire.XLS for Python stands out by offering a complete Excel feature set.

Capability Open-Source Libraries Spire.XLS for Python
Advanced Excel formatting Basic styling Full styling API for reports
No Office/COM dependency Fully standalone Fully standalone
Supports .xls, .xlsx, .csv .xlsx and .csv mostly; .xls may need extra packages Full support for .xls, .xlsx, .csv
Charts, images, shapes Limited or none Built-in full support

For developer teams that need polished Excel files — with complex layouts, visuals, or business-ready styling — Spire.XLS is an efficient, all-in-one alternative.


Convert JSON to Excel in Python

In this section, we’ll walk through how to convert structured JSON data into an Excel file using Python. This is especially useful when exporting API responses or internal data into .xlsx reports for business users or analysts.

Step 1: Prepare JSON Data

We’ll start with a JSON list of employee records:

[
  {"employee_id": "E001", "name": "Jane Doe", "department": "HR"},
  {"employee_id": "E002", "name": "Michael Smith", "department": "IT"},
  {"employee_id": "E003", "name": "Sara Lin", "department": "Finance"}
]

This is a typical structure returned by APIs or stored in log files. For more complex nested structures, see the real-world example section.

Step 2: Convert JSON to Excel in Python with Spire.XLS

from spire.xls import Workbook, FileFormat
import json

# Load JSON data from file
with open("employees.json", "r", encoding="utf-8") as f:
    data = json.load(f)

# Create a new Excel workbook and access the first worksheet
workbook = Workbook()
sheet = workbook.Worksheets[0]

# Write headers to the first row
headers = list(data[0].keys())
for col, header in enumerate(headers):
    sheet.Range[1, col + 1].Text = header

# Write data rows starting from the second row
for row_idx, row in enumerate(data, start=2):
    for col_idx, key in enumerate(headers):
        sheet.Range[row_idx, col_idx + 1].Text = str(row.get(key, ""))

# Auto-fit the width of all used columns
for i in range(1, sheet.Range.ColumnCount + 1):
    sheet.AutoFitColumn(i)

# Save the Excel file and release resources
workbook.SaveToFile("output/employees.xlsx", FileFormat.Version2016)
workbook.Dispose()

Code Explanation:

  • Workbook() initializes the Excel file with three default worksheets.
  • workbook.Worksheets[] accesses the specified worksheet.
  • sheet.Range(row, col).Text writes string data to a specific cell (1-indexed).
  • The first row contains column headers based on JSON keys, and each JSON object is written to a new row beneath it.
  • workbook.SaveToFile() saves the Excel workbook to disk. You can specify the format using the FileFormat enum — for example, Version97to2003 saves as .xls, Version2007 and newer save as .xlsx, and CSV saves as .csv.

The generated Excel file (employees.xlsx) with columns employee_id, name, and department.

Export JSON to Excel in Python

You can also convert the Excel worksheet to a CSV file using Spire.XLS for Python if you need a plain text output format.


Convert Excel to JSON in Python

This part explains how to convert Excel data back into structured JSON using Python. This is a common need when importing .xlsx files into web apps, APIs, or data pipelines that expect JSON input.

Step 1: Load the Excel File

First, we use Workbook.LoadFromFile() to load the Excel file, and then select the worksheet using workbook.Worksheets[0]. This gives us access to the data we want to convert into JSON format.

from spire.xls import Workbook

# Load the Excel file
workbook = Workbook()
workbook.LoadFromFile("products.xlsx")
sheet = workbook.Worksheets[0]

Step 2: Extract Excel Data and Write to JSON

import json

# Get the index of the last row and column
rows = sheet.LastRow
cols = sheet.LastColumn

# Extract headers from the first row
headers = [sheet.Range[1, i + 1].Text for i in range(cols)]
data = []

# Map each row to a dictionary using headers
for r in range(2, rows + 1):
    row_data = {}
    for c in range(cols):
        value = sheet.Range[r, c + 1].Text
        row_data[headers[c]] = value
    data.append(row_data)

# Write JSON output
with open("products_out.json", "w", encoding="utf-8") as f:
    json.dump(data, f, indent=2, ensure_ascii=False)

Code Explanation:

  • sheet.LastRow and sheet.LastColumn detect actual used cell range.
  • The first row is used to extract field names (headers).
  • Each row is mapped to a dictionary, forming a list of JSON objects.
  • sheet.Range[row, col].Text returns the cell’s displayed text, including any formatting (like date formats or currency symbols). If you need the raw numeric value or a real date object, you can use .Value, .NumberValue, or .DateTimeValue instead.

The JSON file generated from the Excel data using Python:

Excel to JSON using Python

If you’re not yet familiar with how to read Excel files in Python, see our full guide: How to Read Excel Files in Python Using Spire.XLS.


Real-World Example: Handling Nested JSON and Formatting Excel

In real-world Python applications, JSON data often contains nested dictionaries or lists, such as contact details, configuration groups, or progress logs. At the same time, the Excel output is expected to follow a clean, readable layout suitable for business or reporting purposes.

In this section, we'll demonstrate how to flatten nested JSON data and format the resulting Excel sheet using Python and Spire.XLS. This includes merging cells, applying styles, and auto-fitting columns — all features that help present complex data in a clear tabular form.

Let’s walk through the process using a sample file: projects_nested.json.

Step 1: Flatten Nested JSON

Sample JSON file (projects_nested.json):

[
  {
    "project_id": "PRJ001",
    "title": "AI Research",
    "manager": {
      "name": "Dr. Emily Wang",
      "email": "[email protected]"
    },
    "phases": [
      {"phase": "Design", "status": "Completed"},
      {"phase": "Development", "status": "In Progress"}
    ]
  },
  {
    "project_id": "PRJ002",
    "title": "Cloud Migration",
    "manager": {
      "name": "Mr. John Lee",
      "email": "[email protected]"
    },
    "phases": [
      {"phase": "Assessment", "status": "Completed"}
    ]
  }
]

We'll flatten all nested structures, including objects like manager, and summarize lists like phases into string fields. Each JSON record becomes a single flat row, with even complex nested data compactly represented in columns using readable summaries.

import json

# Helper: Flatten nested data and summarize list of dicts into strings
# e.g., [{"a":1},{"a":2}] → "a: 1; a: 2"
def flatten(data, parent_key='', sep='.'):
    items = {}
    for k, v in data.items():
        new_key = f"{parent_key}{sep}{k}" if parent_key else k
        if isinstance(v, dict):
            items.update(flatten(v, new_key, sep=sep))
        elif isinstance(v, list):
            if all(isinstance(i, dict) for i in v):
                items[new_key] = "; ".join(
                    ", ".join(f"{ik}: {iv}" for ik, iv in i.items()) for i in v
                )
            else:
                items[new_key] = ", ".join(map(str, v))
        else:
            items[new_key] = v
    return items

# Load and flatten JSON
with open("projects_nested.json", "r", encoding="utf-8") as f:
    raw_data = json.load(f)

flat_data = [flatten(record) for record in raw_data]

# Collect all unique keys from flattened data as headers
all_keys = set()
for item in flat_data:
    all_keys.update(item.keys())
headers = list(sorted(all_keys))  # Consistent, sorted column order

This version of flatten() converts lists of dictionaries into concise summary strings (e.g., "phase: Design, status: Completed; phase: Development, status: In Progress"), making complex structures more compact for Excel output.

Step 2: Format and Export Excel with Spire.XLS

Now we’ll export the flattened project data to Excel, and use formatting features in Spire.XLS for Python to improve the layout and readability. This includes setting fonts, colors, merging cells, and automatically adjusting column widths for a professional report look.

from spire.xls import Workbook, Color, FileFormat

# Create workbook and worksheet
workbook = Workbook()
sheet = workbook.Worksheets[0]
sheet.Name = "Projects"

# Title row: merge and style
col_count = len(headers)
sheet.Range[1, 1, 1, col_count].Merge()
sheet.Range[1, 1].Text = "Project Report (Flattened JSON)"
title_style = sheet.Range["A1"].Style
title_style.Font.IsBold = True
title_style.Font.Size = 14
title_style.Font.Color = Color.get_White()
title_style.Color = Color.get_DarkBlue()

# Header row from flattened keys
for col, header in enumerate(headers):
    cell = sheet.Range[2, col + 1]
    cell.BorderAround() # Add outside borders to a cell or cell range
    #cell.BorderInside() # Add inside borders to a cell range
    cell.Text = header
    style = cell.Style
    style.Font.IsBold = True
    style.Color = Color.get_LightGray()

# Data rows
for row_idx, row in enumerate(flat_data, start=3):
    for col_idx, key in enumerate(headers):
        sheet.Range[row_idx, col_idx + 1].Text = str(row.get(key, ""))

# Auto-fit columns and rows
for col in range(len(headers)):
    sheet.AutoFitColumn(col + 1)
for row in range(len(flat_data)):
    sheet.AutoFitRow(row + 1)

# Save Excel file
workbook.SaveToFile("output/projects_formatted.xlsx", FileFormat.Version2016)
workbook.Dispose()

This produces a clean, styled Excel sheet from a nested JSON file, making your output suitable for reports, stakeholders, or dashboards.

Code Explanation

  • sheet.Range[].Merge(): merges a range of cells into one. Here we use it for the report title row (A1:F1).
  • .Style.Font / .Style.Color: allow customizing font properties (bold, size, color) and background fill of a cell.
  • .BorderAround() / .BorderInside(): add outside/inside borders to a cell range.
  • AutoFitColumn(n): automatically adjusts the width of column n to fit its content.

The Excel file generated after flattening the JSON data using Python:

Nested JSON converted to formatted Excel in Python


Common Errors and Fixes in JSON ↔ Excel Conversion

Converting between JSON and Excel may sometimes raise formatting, encoding, or data structure issues. Here are some common problems and how to fix them:

Error Fix
JSONDecodeError or malformed input Ensure valid syntax; avoid using eval(); use json.load() and flatten nested objects.
TypeError: Object of type ... is not JSON serializable Use json.dump(data, f, default=str) to convert non-serializable values.
Excel file not loading or crashing Ensure the file is not open in Excel; use the correct extension (.xlsx or .xls).
UnicodeEncodeError or corrupted characters Set encoding="utf-8" and ensure_ascii=False in json.dump().

Conclusion

With Spire.XLS for Python, converting between JSON and Excel becomes a streamlined and reliable process. You can easily transform JSON data into well-formatted Excel files, complete with headers and styles, and just as smoothly convert Excel sheets back into structured JSON. The library helps you avoid common issues such as encoding errors, nested data complications, and Excel file format pitfalls.

Whether you're handling data exports, generating reports, or processing API responses, Spire.XLS provides a consistent and efficient way to work with .json and .xlsx formats in both directions.

Want to unlock all features without limitations? Request a free temporary license for full access to Spire.XLS for Python.

FAQ

Q1: How to convert JSON into Excel using Python?

You can use the json module in Python to load structured JSON data, and then use a library like Spire.XLS to export it to .xlsx. Spire.XLS allows writing headers, formatting Excel cells, and handling nested JSON via flattening. See the JSON to Excel section above for step-by-step examples.

Q2: How do I parse JSON data in Python?

Parsing JSON in Python is straightforward with the built-in json module. Use json.load() to parse JSON from a file, or json.loads() to parse a JSON string. After parsing, the result is usually a list of dictionaries, which can be iterated and exported to Excel or other formats.

Q3: Can I export Excel to JSON with Spire.XLS in Python?

Yes. Spire.XLS for Python lets you read Excel files and convert worksheet data into a list of dictionaries, which can be written to JSON using json.dump(). The process includes extracting headers, detecting used rows and columns, and optionally handling formatting. See Excel to JSON for detailed implementation.