Skip to main content

Generate Excel Chart from JSON Data

Incoming JSON Data to Python Operations


{
  "chart_data": [
    {
      "label": "January",
      "value": 150
    },
    {
      "label": "February",
      "value": 220
    }
  ]
}
Python Operations

import pandas as pd
from io import BytesIO
import base64

from openpyxl import Workbook
from openpyxl.chart import BarChart, Reference

Responsedata = []

# Read incoming JSON data
data = pycode_data.get("chart_data", [])

# Create workbook and worksheet
wb = Workbook()
ws = wb.active
ws.title = "Chart Data"

# Add column headers
ws.append(["Label", "Value"])

# Populate worksheet with data
for row in data:
    ws.append([row["label"], row["value"]])

# Create a chart
chart = BarChart()

# Configure chart data range
data_range = Reference(ws, min_col=2, min_row=1, max_row=len(data) + 1)
category_range = Reference(ws, min_col=1, min_row=2, max_row=len(data) + 1)

# Add data and categories to chart
chart.add_data(data_range, titles_from_data=True)
chart.set_categories(category_range)

# Add chart to worksheet
ws.add_chart(chart, "E2")

# Save workbook to memory
output = BytesIO()
wb.save(output)

# Encode workbook as Base64
output.seek(0)
file_content = base64.b64encode(output.read()).decode()

# Prepare output response
response = {
    "file_name": "Excel_Chart.xlsx",
    "file_content": file_content,
    "mime_type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
}

# Send data to output
Responsedata.append(response)
Outgoing data from Python Operation

{
  "file_name": "Excel_Chart.xlsx",
  "file_content": "<Base64 Encoded Content>",
  "mime_type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
}