- a Python module to easily generate HTML tables and lists has been developed to easily generate HTML code for tables and lists in Python scripts. This is mostly convenient to generate reports in HTML or simple web applications in lightweight frameworks such as CherryPy.

There are already quite a few similar solutions for Python, either HTML generators or templating engines (see links at the end of this article). Most of them are very powerful but quite complex for simple cases. is useful when you need to generate simple HTML code without requiring to learn a templating language. Furthermore, while some HTML generators provide a comprehensive object-oriented model of HTML, is meant to translate Python objects to HTML as easily as possible.


Click on the attached file below at the bottom of this page.


Cecill: open-source, GPL compatible.

How to use

Basic principles

The HTML module provides two different interfaces: classes (Table, List, ...) and functions with similar names in lowercase (table, list, ...). Functions simply translate Python data to HTML source code in a string, while classes are a representation of data which may be modified in place and rendered as HTML code when needed. For simple tasks functions are easier to use, while classes provide more flexibility.

HTML Tables

Basically, an HTML table is stored as a list of rows. Each row is itself a list of cells. Each cell is a Python string or any object which may be rendered as a string using str().

So the easiest way to create a HTML table is to use a list of lists:

import HTML
table_data = [
        ['Last name',   'First name',   'Age'],
        ['Smith',       'John',         30],
        ['Carpenter',   'Jack',         47],
        ['Johnson',     'Paul',         62],
htmlcode = HTML.table(table_data)
print htmlcode

A header row may be specified: it will appear in bold in browsers

table_data = [
        ['Smith',       'John',         30],
        ['Carpenter',   'Jack',         47],
        ['Johnson',     'Paul',         62],

htmlcode = HTML.table(table_data,
    header_row=['Last name',   'First name',   'Age'])
print htmlcode

You may also create a Table object and add rows one by one. Its "rows" attribute is a list which can be modified in place. When the table is complete, convert the Table object to a string using str() to get the HTML code:

t = HTML.Table(header_row=['x', 'square(x)', 'cube(x)'])
for x in range(1,10):
    t.rows.append([x, x*x, x*x*x])
htmlcode = str(t)
print htmlcode

Rows may be any iterable (list, tuple, ...) including a generator. This is useful to save memory when generating a large table.

def gen_rows(i):
    'rows generator'
    for x in range(1,i):
        yield [x, x*x, x*x*x]
htmlcode = HTML.table(gen_rows(10), header_row=['x', 'square(x)', 'cube(x)'])
print htmlcode

To choose a specific background color for a cell, use a TableCell object:

HTML_COLORS = ['Black', 'Green', 'Silver', 'Lime', 'Gray', 'Olive', 'White',
    'Maroon', 'Navy', 'Red', 'Blue', 'Purple', 'Teal', 'Fuchsia', 'Aqua']
t = HTML.Table(header_row=['Name', 'Color'])
for colorname in HTML_COLORS:
    colored_cell = HTML.TableCell(' ', bgcolor=colorname)
    t.rows.append([colorname, colored_cell])
htmlcode = str(t)
print htmlcode

Here is an example of how can be used to generate a test report with colors for successes, failures and errors:

# dictionary of test results, indexed by test id:
test_results = {
        'test 1': 'success',
        'test 2': 'failure',
        'test 3': 'success',
        'test 4': 'error',
# dict of colors for each result:
result_colors = {
        'success':      'lime',
        'failure':      'red',
        'error':        'yellow',
t = HTML.Table(header_row=['Test', 'Result'])
for test_id in sorted(test_results):
    # create the colored cell:
    color = result_colors[test_results[test_id]]
    colored_result = HTML.TableCell(test_results[test_id], bgcolor=color)
    # append the row with two cells:
    t.rows.append([test_id, colored_result])
htmlcode = str(t)
print htmlcode

HTML Lists

a HTML list (with bullets) may simply be built from a Python list of strings:

a_list = ['john', 'paul', 'jack']
htmlcode = HTML.list(a_list)
print htmlcode

It is easy to change it into a numbered (ordered) list:

htmlcode = HTML.list(a_list, ordered=True)
print htmlcode

Lines of a list may also be added one by one, when using the List class. Its "lines" attribute can be modified in place:

html_list = HTML.List()
for i in range(1,10):
    html_list.lines.append('square(%d) = %d' % (i, i*i))
htmlcode = str(html_list)
print htmlcode

To save memory, a large list may also be built from a generator:

def gen_lines(i):
    'lines generator'
    for x in range(1,i):
        yield 'square(%d) = %d' % (x, x*x)
htmlcode = HTML.list(gen_lines(10))
print htmlcode

HTML Links

How to create a link:

htmlcode ='Decalage website', '')
print htmlcode tutorial

All the examples above may be tested using the script provided with


If does not suit your needs, there are quite a few other solutions to generate HTML from Python:

HTML generators:

Templating engines:


AttachmentSize KB


Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes. - adding header_styles and td_styles parameters

I,ve needed to do some tables, so I used your modul HTML but changed it a bit. Now it's quite easy to make tables with various styles:

t = HTML.Table(header_row= ['č.b.', 'jméno', 'podíl', 'první vhodné datum', 'druhé vhodné datum', 'podpis'],
header_styles=('width: 3%', 'width: 25%', 'width: 5%', 'width: 12%', 'width: 12%', 'width: 15%' ),
td_styles= ('text-align: right', '', 'text-align: right', '', '', '' ))
for byt, podil, jmeno in naj:
t.rows.append([byt, jmeno, podil, '', ''])
htmlcode = str(t). Are you interested?

Kind regards Michal

Added column styles, width and alignment

Michal, I've improved thanks to your ideas and code proposal. The Table class in 0.04 provides new attributes to set width, alignment and style for each column. The implementation is slightly different from the one you proposed in order to keep it simple and extensible, but it should provide the same results.

At first I wanted to use the simple <COL> tags according to HTML 4.01 specs, but after some time I realized I was hitting one of the oldest and trickiest bugs in Mozilla and Firefox!:

That's why in the end column width and styles are added to each cell, in order to accomodate with browser bugs...



i use your module and it works very well. Now I've tried to use HTMLGen from this website

But it uses regex and and regsub. I think these modules are old an no longer supported in the actual python (2.6). Do you have a running version of HTMLGen??



Indeed HTMLGen is quite old and it has not been updated since 2001. It would have to be modified to run with latest Python versions (2.5+), at least by using the re module instead of regex/regsub. Sorry, I haven't found any fixed version so far.



Just testing out on a mac. So far works great - nice and simple.

Feature request 'image' class -I tend to add images to tables, beyond that it has everything I need.

Right now to get the desired output I would add my image to a cell in the table class and string replace the html output

old image name:


loop over the html created by

newHtml = oldHtml.replace('replacePrefix_', '')

This will work but is a little clumsy - having an image class, like the link class would be great.


Images in table cells

Hi cl,

I'm not exactly sure what you need to do, but at least you may simply use any "raw" HTML inside each cell. For example if you want to insert an image, you may use something like this:

mytable.rows.append(['image 1', '<img src="img1.jpg">'])

Of course it would be easy to create a new function similar to in order to create image tags. I'll think of it for the next version of

Thank you for your feedback,


Image in cell


2 years later the first post, I propose the simple function below, similar to, in order to insert image tag :

def image(text, url):
    return "<center>%s</center><img src='%s'>" % (text, url)

This function can be insert in the user module (no need to wait the next version of

Thanks for sharing this module which does well the simple work I needed


Creating several pages in a single document


I want to create a html document such that it has several pages of data. How do I create different pages within the same document? What is the method for that?

Or is it necessary to create several docs and then link it?

Several pages in a single HTML document

A basic HTML document can only be one page. However, you may use JavaScript and CSS to change the displayed content when the user clicks on a link or a tab, giving the illusion of several pages in one (see this example). Another possibility is to have all the text in the same page and choose which part to display according to the URL thanks to PHP (see that example). Google is your friend.

Few Queries


Is there any option for changing the font style and font color of the text that gets displayed in the HTML sheet?

Is there any scope for alignment of text data which is passed into the HTML sheet using the HTML.list() method? Say a particular header needs to be center aligned.

Also, can linking within the various sections of text in the same page be done using method? If not, how can it be achieved?

a few answers

There are many options to set font styles and colors in various places of a HTML page, but this question is more about HTML in general than itself. Look for "html font" and "html css" in your favorite search engine, there are many useful tutorials to start with.

You may use styles in objects when they have a "style" attribute, or else using the "attribs" attribute. For example:

a_list = ['john', 'paul', 'jack']
htmlcode = HTML.list(a_list, attribs={'style': 'font-family: Helvetica, Arial, sans-serif'})

To answer your second question, you may add a style attribute to a list so that it is centered:

htmlcode = HTML.list(a_list, attribs={'style': 'text-align: center'})

To create links which point to other sections in the same page, just use anchors with a name attribute, and then links such as "#name". Example:

<a name="section1">SECTION 1</a>
<a href="#section1">link to section 1</a>



I have used to create several HTML sheets. However, one sheet among it acts like the Main Page which has links to the rest of the sheets. The rest of the sheets apart from the main sheet are inside a sub-folder. Thus, the main folder consists of the Main Page and the sub-folder.

The links in the Main Page direct to the various other pages really well when the Python code is compiled on Linux. However, when just the output alone was checked on Windows platform, the links do not work.

The method seems to be system specific. Can you please suggest what can be done in this regard so that the links work in any platform?

Is there any alternative apart from using the actual hyperlinks using href and name? That would be more of HTML coding than Python

Thank you

HTML links just creates HTML links with the URLs you provide, so the syntax should not depend on the OS. Please send me an e-mail at decalage(a) with an example of your code, I'll see what the exact issue is.

Generating Tables, reports


Thanks for this great library. I have started to write a table generator function after some failures i found your ready made library. So i'm writing a program which makes some reports about one firm sales. They have 2 big different categories. A would like to make a table with some cols appearing with different background color.
I have all of the displayable data in one big list (sales day by day since january 1). Can i somehow change the color of columns but not with regenerating all of the data with using TableCell -s?

Sorry for my bad english and thanks in advance.

Using column styles to set background color

Hi, one solution to do it is to use the col_styles option to set the background color for each column using CSS styles, for example like this:

table_data = [['Smith',       'John',         30],
              ['Carpenter',   'Jack',         47],
              ['Johnson',     'Paul',         62]]
htmlcode = HTML.table(table_data,
    header_row = ['Last name',   'First name',   'Age'],
    col_align  = ['left', 'center', 'right'],
    col_styles = [None, None, 'background-color:lightblue;'])

Generating Multi Level Lists

Iam searching for an eays way to generate a multi Level HTML List from a Python Data Structure.
For Examlpe
something like this(or maybe another kind of tree structure)
[boys, girls]
boys=['John','Paul'] girls=['Linda','Jane']
into this

  • Boys

    • john
    • Paul

  • Girls

    • Linda
    • Jane

Any Ideas how to realize something like this?

Nested lists

Good point, to do this in plain HTML you just need to create nested lists. The syntax you proposed (nested Python lists) is not directly supported by 0.04 yet. I might add it to a future version, because it should not be too complex.

However, you can already obtain the same result with the following "hack", by nesting HTML.list calls (pay attention to the "+"):

boys  = HTML.list(['John','Paul'])
girls = HTML.list(['Linda','Jane'])
htmlcode = HTML.list(['Boys'+boys, 'Girls'+girls])

Creating nested tables with different background colors

I am trying to create two tables within a table with
The code I am trying to produce looks like


In addition, I need the background colors of the tables to be different. Is there any way to define the bgcolor within HTML.table?

Any advice on how to do the above with HTML.table?

Many thanks in advance.

How to create nested tables with different background colors

HooLooVoo, here is a solution: to create nested tables, just use a Table object as a cell. And to set the background color of a table, you may add the bgcolor attribute by providing it in the attribs dictionary. Here is an example:

table_data = [['A', 'B'],
              [ 1,   2 ]]
table1 = HTML.Table(table_data, attribs={'bgcolor': 'yellow'})
table2 = HTML.Table(table_data, attribs={'bgcolor': 'orange'})
table =  HTML.Table(attribs={'bgcolor': 'lime'})
table.rows = [[table1],
htmlcode = str(table)


Defining a background color for the Header row.

The header row is given by e.g. t = HTML.Table(header_row=['x', 'square(x)', 'cube(x)'])
I would like to specify a background color for it as well. Is there a way to do that or does the header always have to appear on a white background?

Thanks in advance,

How to set the background color of a header row

You may specify a background color for the header row, by using a TableRow object instead of a list. For example:

t =  HTML.Table(header_row = HTML.TableRow(['x', 'square(x)', 'cube(x)'], bgcolor='yellow'))

changed the __str__ () methods to work with unicode strings

With the objective to pass "iso-8859-15" strings through the I modified the __str__ methods. Please provide a email-adress and I will send you my version. regards B.

unicode patch

Hi Behrmi, please send your patch to decalage (at) laposte (dot) net. Thanks a lot for contributing!

just thank you note...

Ahoy matey decalage!

Thank you for share this module with the community.
I am using it, it works great and so far is exactly what i need.

Fede run under apache on windows

If you encounter the any problem running python classes under apache on windows you can type this line in the script after "import HTML" : << print "Content-Type: text/html\n" >>. This may sound noobish, but took a while to figure out.

0 value or empty cells


I'm using to create basic HTML tables from (possibly complex) Excel spreadsheets by way of xlrd. An error I'm encountering is that 0 values and empty cells seem to be treated the same.

I pass this row:
[9.0, u'Powell River', 0.0, 0.0, 0.0, 0.0, '', '', u'Not Expected', u'Not Expected', u'No Emission Factor', u'No Emission Factor', u'Not Expected', u'Not Expected']

to t.rows.append, and get:

  <TD>Powell River</TD>
  <TD>Not Expected</TD>
  <TD>Not Expected</TD>
  <TD>No Emission Factor</TD>
  <TD>No Emission Factor</TD>
  <TD>Not Expected</TD>
  <TD>Not Expected</TD>

0 value or empty cells

Changed line 148 to:

if self.text or self.text == 0:

to account for 0 values in cells showing.



thank you a lot for your module. Is there a way to use the colspan attribute for a certain row?
Kind regards

How to add the colspan attribute for a cell

You may add the colspan attribute to a cell by using the HTML.TableCell class with the attribs parameter, for example:

table_data = [
        [HTML.TableCell('test colspan', attribs={'colspan':2}), 'other cell'],
        ['Last name',   'First name',   'Age'],
        ['Smith',       'John',         30],
        ['Carpenter',   'Jack',         47],
htmlcode = HTML.table(table_data)
print htmlcode

Code change color.

Down, the code for print table with diferent colours.

COLORS = [['xxxxxxxxxx', 1], ['aaaaaaaaa', 1043], ['qqqqqqq', 12513], ['ssssss', 900], ['qqqqqqq', 1895], ['uuuuuuu', 4073]]
esp = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'
t = HTML.Table(header_row=['%s%s%sSTO%s%s%s' % (esp,esp,esp,esp, esp,esp), '%sGB%s' % (esp, esp)], attribs={'bgcolor': 'silver'})
for i in COLORS:
       if n % 2 == 0:
                colored_cell = HTML.TableCell(i[0], bgcolor='white')
                colored_cell1 = HTML.TableCell(i[1], bgcolor='white')
               colored_cell = HTML.TableCell(i[0], bgcolor='lightblue')
               colored_cell1 = HTML.TableCell(i[1], bgcolor='lightblue')
        t.rows.append([colored_cell, colored_cell1])
mia = str(t)
print mia
print mia

How to Merge two cells

That is to say the number of columns of the header row is less than that of other rows.
For example, how can I create table like the table named "A test table with merged cells" in the following link:

Is it possible to have

Is it possible to have output lowecase tags? Like < tr > instead of < TR >?


How can I change cellpadding for an entire table?

Turn off the internal grid of the table

Is there a way to turn off the internal grid so that the table resembles a rectangle.

I would like to use your html generator solution to design PDF files.

By the way I like this solution very much!


Hello, I have a really big


I have a really big sqlite database and wanted to generate an html file from it using python script on linux platform. Please let me know.
I have tried module but i cannot write the html code for that big database and wanted html file to be generated automatically. Please help me out.