Create an HTML table, but with Python

If you don’t like to write a lot of code to make a table in html, you can use this code in Python to do it for you:

# simple table
from random import randrange
import os


def wrap(a, tag):
    "Wraps in <td> tag the a"
    tag1 = tag
    if tag == "table":
        tag1 = "table border=1"
    if tag == "td" and a.strip().replace(".", "").isdigit():
        print(a, "è un numero")
        tag1 = "td style=\"text-align:right\""
    return f"<{tag1}>{a}</{tag}>"


def split(tab):
    "Splits a multiline string in a list of items divided by comma for line"
    tab = tab.splitlines()
    for n, row in enumerate(tab):
        tab[n] = row.split(",")
    return tab


def table(tab):
    html = ''  # contain html
    for n, x in enumerate(tab):
        for a in x:
            html += wrap(a, "td")
        html += "<tr>"
    html = wrap(html, "table")
    return html


data = table(split("""
Impiegato, Performance, data
Rossi Mario, 1000, 1/2/2018
Baldo Franco, 2000, 1/2/2018
    """)[1:-1])

with open("Simple.html", "w", encoding="utf-8") as filehtml:
    filehtml.write(data)

os.system("Simple.html")

All you have to do is to change the data into the data variable (in the “””     “”” space), with items separated by commas.

This will be the result.

Impiegato Performance data
Rossi Mario 1000 1/2/2018
Baldo Franco 2000 1/2/2018

Some changes in the code

Lately, I have revisited the code to make it a little more simple and ‘readable’, and with the chance to make row with different colspan. It works for rows with 3 columns that are sometimes 2 colums (the latter will be colspan=2).

from random import randrange
import os
 
 
def wrap(a, tag):
    "Wraps in <td> tag the a"
    tag1 = tag
    if tag == "table":
        tag1 = "table border=1"
    if tag == "td" and a.strip().replace(".", "").isdigit():
        print(a, "è un numero")
        tag1 = "td style=\"text-align:right\""
    return f"<{tag1}>{a}</{tag}>"
 
 
cspan = 0 
 
def createHtmlCode(data):
    global cspan
    htmltable = ''  # contain the table tags & data
    num_row = len(data[0].split(",")) # Cols from row1
    for n, row in enumerate(data): # for all rows
    # now every rows become a list (data = [[...][...])
        data[n] = row.split(",")
    for n, x in enumerate(data):
        for a in x:
            if len(x) == num_row: # if data i row == 3
                htmltable += wrap(a, "td")
            else: # if data < 3
                if cspan == 0:
                    htmltable += wrap(a, "td")
                    cspan += 1
                else:
                    htmltable += wrap(a, "td style='text-align:center' colspan=" + str(num_row-len(x)+1))
                    cspan = 0
        htmltable += "<tr>"
    htmltable = wrap(htmltable, "table")
    return htmltable
 
 
data = """
Descrizione,        Coniugi Martini, Coniugi Alessandri
Numero di invitati, 120,             280
Alimenti e bevande, 5000,            7900
Lavoro diretto,     500,             600
lavoro indiretto,   900
ammortamenti,       300
amministrazione,    2300
    """.splitlines()[1:-1]
 
data = createHtmlCode(data)
 
with open("Simple.html", "w", encoding="utf-8") as filehtml:
    filehtml.write(data)
 
os.system("Simple.html")

The output:

Descrizione Coniugi Martini Coniugi Alessandri
Numero di invitati 120280
Alimenti e bevande50007900
Lavoro diretto500600
lavoro indiretto900
ammortamenti300
amministrazione2300

 

Creare una tabella html in Python

More recent post about this topic:

Click here to read the post about making html code for a table with Python.

Another post about this topic

Another post about this topic

Another post about this topic

Utilities

[contact-form][contact-field label=”Name” type=”name” required=”true” /][contact-field label=”Email” type=”email” required=”true” /][contact-field label=”Website” type=”url” /][contact-field label=”Message” type=”textarea” /][/contact-form]

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.