TABLE

Excel Usage

=TABLE(data, title, col_colors, cell_colors)
  • data (list[list], required): Input data.
  • title (str, optional, default: null): Table title.
  • col_colors (str, optional, default: null): Header colors (comma-separated or single color).
  • cell_colors (str, optional, default: null): Cell colors (comma-separated or single color).

Returns (object): Matplotlib Figure object (standard Python) or base64 encoded PNG string (Pyodide).

Examples

Example 1: Basic 3x3 table

Inputs:

data
Name Age City
Alice 30 NYC
Bob 25 LA

Excel formula:

=TABLE({"Name","Age","City";"Alice",30,"NYC";"Bob",25,"LA"})

Expected output:

"chart"

Example 2: Table with title

Inputs:

data title
Product Price Stock Inventory
Widget 9.99 100
Gadget 19.99 50

Excel formula:

=TABLE({"Product","Price","Stock";"Widget",9.99,100;"Gadget",19.99,50}, "Inventory")

Expected output:

"chart"

Example 3: Colored column headers

Inputs:

data col_colors
Q1 Q2 Q3 Q4 lightblue
100 150 200 250

Excel formula:

=TABLE({"Q1","Q2","Q3","Q4";100,150,200,250}, "lightblue")

Expected output:

"chart"

Example 4: Colored cells with alternating colors

Inputs:

data cell_colors
A B lightgray,white
1 2
3 4

Excel formula:

=TABLE({"A","B";1,2;3,4}, "lightgray,white")

Expected output:

"chart"

Python Code

import sys
import matplotlib
IS_PYODIDE = sys.platform == "emscripten"
if IS_PYODIDE:
    matplotlib.use('Agg')
import matplotlib.pyplot as plt
import io
import base64
import numpy as np

def table(data, title=None, col_colors=None, cell_colors=None):
    """
    Render data as a graphical table image.

    See: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.table.html

    This example function is provided as-is without any representation of accuracy.

    Args:
        data (list[list]): Input data.
        title (str, optional): Table title. Default is None.
        col_colors (str, optional): Header colors (comma-separated or single color). Default is None.
        cell_colors (str, optional): Cell colors (comma-separated or single color). Default is None.

    Returns:
        object: Matplotlib Figure object (standard Python) or base64 encoded PNG string (Pyodide).
    """
    def to2d(x):
        return [[x]] if not isinstance(x, list) else x

    try:
        data = to2d(data)

        if not isinstance(data, list) or len(data) == 0:
            return "Error: Data must be a non-empty 2D list"

        # Convert data to strings for display
        table_data = []
        for row in data:
            if isinstance(row, list):
                table_data.append([str(cell) if cell is not None else "" for cell in row])
            else:
                table_data.append([str(row)])

        if len(table_data) == 0:
            return "Error: No valid data found"

        # Determine dimensions
        max_cols = max(len(row) for row in table_data)

        # Pad rows to have equal length
        for row in table_data:
            while len(row) < max_cols:
                row.append("")

        # Create the figure
        fig, ax = plt.subplots(figsize=(max(8, max_cols * 1.5), max(4, len(table_data) * 0.5)))
        ax.axis('tight')
        ax.axis('off')

        # Parse column colors
        col_color_list = None
        if col_colors:
            colors = [c.strip() for c in str(col_colors).split(',')]
            if len(colors) == 1:
                col_color_list = [colors[0]] * max_cols
            else:
                col_color_list = colors[:max_cols]
                while len(col_color_list) < max_cols:
                    col_color_list.append(col_color_list[-1] if col_color_list else 'lightgray')

        # Parse cell colors
        cell_color_list = None
        if cell_colors:
            colors = [c.strip() for c in str(cell_colors).split(',')]
            if len(colors) == 1:
                cell_color_list = [[colors[0]] * max_cols for _ in table_data]
            else:
                # Apply colors row by row
                cell_color_list = []
                for i in range(len(table_data)):
                    row_colors = []
                    for j in range(max_cols):
                        idx = (i * max_cols + j) % len(colors)
                        row_colors.append(colors[idx])
                    cell_color_list.append(row_colors)

        # Create table
        table = ax.table(cellText=table_data, loc='center',
                        colColours=col_color_list,
                        cellColours=cell_color_list,
                        cellLoc='center')

        table.auto_set_font_size(False)
        table.set_fontsize(10)
        table.scale(1, 2)

        if title:
            plt.title(str(title), pad=20, fontsize=14, weight='bold')

        plt.tight_layout()

        if IS_PYODIDE:
            buf = io.BytesIO()
            plt.savefig(buf, format='png', dpi=100, bbox_inches='tight')
            buf.seek(0)
            img_base64 = base64.b64encode(buf.read()).decode('utf-8')
            plt.close(fig)
            return f"data:image/png;base64,{img_base64}"
        else:
            return fig
    except Exception as e:
        return f"Error: {str(e)}"

Online Calculator