HTML Examples

This page provides a list of examples that demonstrate rendering html tables from the given dataframe. Each example is self-contained inside a class. We have some helper functions to provide the data we need for this examples

Helper Functions (Data loading routines)

 1import tempfile
 2import webbrowser
 3import zipfile
 4
 5import pandas as pd
 6import requests
 7
 8import table_compositor.html_styles as html_style
 9import table_compositor.html_writer as htmlw
10import table_compositor.table_compositor as tc
11
 1# code snippet adapted from http://function-pipe.readthedocs.io/en/latest/usage_df.html
 2# source url
 3URL_NAMES = "https://www.ssa.gov/oact/babynames/names.zip"
 4ZIP_NAME = "names.zip"
 5
 6
 7def load_names_data():
 8    fp = os.path.join(tempfile.gettempdir(), ZIP_NAME)
 9    if not os.path.exists(fp):
10        r = requests.get(URL_NAMES)
11        with open(fp, "wb") as f:
12            f.write(r.content)
13
14    post = collections.OrderedDict()
15    with zipfile.ZipFile(fp) as zf:
16        # get ZipInfo instances
17        for zi in sorted(zf.infolist(), key=lambda zi: zi.filename):
18            fn = zi.filename
19            if fn.startswith("yob"):
20                year = int(fn[3:7])
21                df = pd.read_csv(
22                    zf.open(zi), header=None, names=("name", "gender", "count")
23                )
24                df["year"] = year
25                post[year] = df
26
27        df = pd.concat(post.values())
28        df.set_index("name", inplace=True, drop=True)
29        return df
30
31
32def sample_names_data():
33    df = load_names_data()
34    df = df[(df["year"] == 2015) & (df["count"] > 1000)]
35    return df.sample(50, random_state=0).sort_values("count")
36
37
38def top_names_for_year(year=2015, gender="F", top_n=5):
39    df = load_names_data()
40    df = df[(df["year"] == year) & (df["gender"] == gender)]
41    df = df.sort_values("count")[:top_n]
42    return df
43
44

Example 1 - DataFrame with default styles

Demonstrates converting dataframe into html format with default styles.

 1class HTMLExample1:
 2    """
 3    Demonstrate rendering of a simple dataframe into html
 4    """
 5
 6    @classmethod
 7    def render_html(cls):
 8
 9        # load data
10        df = load_names_data()
11        df = df[:100]
12
13        # build presentation model
14        pm = tc.build_presentation_model(df=df, output_format="html")
15
16        # render to xlsx
17        tempdir = tempfile.gettempdir()
18        fp = os.path.join(tempdir, "example_1.html")
19        layout = [pm]
20        print("Writing to " + fp)
21        html = htmlw.HTMLWriter.to_html(layout, border=1)
22        output_fp = os.path.join(tempfile.gettempdir(), "example1.html")
23        with open(output_fp, "w") as f:
24            f.write(html)
25
26
_images/html_example1.png

Example 2 - DataFrame with custom styles

In this example, we format the different components of dataframe with various styling attributes

  1class HTMLExample2:
  2    """
  3    Demonstrate rendering of a simple dataframe into html
  4    """
  5
  6    @staticmethod
  7    def data_value_func(df):
  8        def _inner(idx, col):
  9            if col == "gender":
 10                if df.loc[idx, col] == "F":
 11                    return "Female"
 12                return "Male"
 13            return df.loc[idx, col]
 14
 15        return _inner
 16
 17    @staticmethod
 18    def data_style_func(df):
 19        def _inner(idx, col):
 20            color = "#FFFFFF"
 21            text_align = "left"
 22            if col == "count":
 23                text_align = "right"
 24            if df.loc[idx, "gender"] == "F":
 25                color = "#bbdef8"
 26            else:
 27                color = "#e3f2fd"
 28            return html_style.td_style(
 29                text_align=text_align,
 30                background_color=color,
 31                color="#000000",
 32                font_weight="normal",
 33                white_space="pre",
 34                padding="10px",
 35                border=None,
 36            )
 37
 38        return _inner
 39
 40    @staticmethod
 41    def index_name_value_func(value):
 42        return value.capitalize()
 43
 44    @staticmethod
 45    def header_value_func(node):
 46        return node.value.capitalize()
 47
 48    @staticmethod
 49    def header_style_func(node):
 50        return html_style.td_style(
 51            text_align="center",
 52            background_color="#4F81BD",
 53            color="#FFFFFF",
 54            font_weight="bold",
 55            white_space="pre",
 56            padding="10px",
 57            border=1,
 58        )
 59
 60    @staticmethod
 61    def index_value_func(node):
 62        return node.value.capitalize()
 63
 64    @staticmethod
 65    def index_style_func(node):
 66        return html_style.td_style(
 67            text_align="center",
 68            background_color="#4F81BD",
 69            color="#FFFFFF",
 70            font_weight="bold",
 71            white_space="pre",
 72            padding="10px",
 73            border=1,
 74        )
 75
 76    @classmethod
 77    def render_html(cls):
 78        # load data
 79        df = sample_names_data()
 80        # build presentation model
 81        klass_ = HTMLExample2
 82        pm = tc.build_presentation_model(
 83            df=df,
 84            output_format="html",
 85            data_value_func=klass_.data_value_func(df),
 86            data_style_func=klass_.data_style_func(df),
 87            header_value_func=klass_.header_value_func,
 88            header_style_func=klass_.header_style_func,
 89            index_style_func=klass_.index_style_func,
 90            index_value_func=klass_.index_value_func,
 91            index_name_func=klass_.index_name_value_func,
 92        )
 93
 94        layout = [pm]
 95        html = htmlw.HTMLWriter.to_html(layout, border=1)
 96        output_fp = os.path.join(tempfile.gettempdir(), "example2.html")
 97        print("Writing to =", output_fp)
 98        with open(output_fp, "w") as f:
 99            f.write(html)
100
101
_images/html_example2.png

Example 3 - Simple DataFrame with Layouts

Demonstrates rendering dataframes with multi-hierarchical indices and mult-hierarchical columns

  1class HTMLExample3:
  2    """
  3    Demonstrate styling and rendering of multiple multi-hierarchical indexed dataframe
  4    into a html file
  5    """
  6
  7    @staticmethod
  8    def data_value_func(df):
  9        def _inner(idx, col):
 10            if col == "gender":
 11                if df.loc[idx, col] == "F":
 12                    return "Female"
 13                return "Male"
 14            return df.loc[idx, col]
 15
 16        return _inner
 17
 18    @staticmethod
 19    def data_style_func(df):
 20        def _inner(idx, col):
 21            color = "#FFFFFF"
 22            text_align = "left"
 23            if col == "count":
 24                text_align = "right"
 25            if df.loc[idx, "gender"] == "F":
 26                color = "#bbdef8"
 27            else:
 28                color = "#e3f2fd"
 29            return html_style.td_style(
 30                text_align=text_align,
 31                background_color=color,
 32                color="#000000",
 33                font_weight="normal",
 34                white_space="pre",
 35                padding="10px",
 36                border=None,
 37            )
 38
 39        return _inner
 40
 41    @staticmethod
 42    def index_name_value_func(value):
 43        return "Max By Year"
 44
 45    @staticmethod
 46    def header_value_func(node):
 47        return node.value.capitalize()
 48
 49    @staticmethod
 50    def header_style_func(node):
 51        return html_style.td_style(
 52            text_align="center",
 53            background_color="#4F81BD",
 54            color="#FFFFFF",
 55            font_weight="bold",
 56            white_space="pre",
 57            padding="10px",
 58            border=1,
 59        )
 60
 61    @staticmethod
 62    def index_value_func(node):
 63        if isinstance(node.value, str):
 64            return node.value.capitalize()
 65        return node.value
 66
 67    @staticmethod
 68    def index_style_func(node):
 69        return html_style.td_style(
 70            text_align="center",
 71            background_color="#4F81BD",
 72            color="#FFFFFF",
 73            font_weight="bold",
 74            white_space="pre",
 75            padding="10px",
 76            border=1,
 77        )
 78
 79    @classmethod
 80    def render_html(cls):
 81
 82        # Prepare first data frame (same as in render_xlsx)
 83        df = sample_names_data()
 84        # build presentation model
 85        klass_ = HTMLExample4
 86        pm_all = tc.build_presentation_model(
 87            df=df,
 88            output_format="html",
 89            data_value_func=klass_.data_value_func(df),
 90            data_style_func=klass_.data_style_func(df),
 91            header_value_func=klass_.header_value_func,
 92            header_style_func=klass_.header_style_func,
 93            index_style_func=klass_.index_style_func,
 94            index_value_func=klass_.index_value_func,
 95            index_name_func=lambda _: "Sample Data",
 96        )
 97
 98        male_df = top_names_for_year(gender="M")
 99        pm_top_male = tc.build_presentation_model(
100            df=male_df,
101            output_format="html",
102            data_value_func=klass_.data_value_func(male_df),
103            data_style_func=klass_.data_style_func(male_df),
104            header_value_func=klass_.header_value_func,
105            header_style_func=klass_.header_style_func,
106            index_style_func=klass_.index_style_func,
107            index_value_func=klass_.index_value_func,
108            index_name_func=lambda _: "Max by Year",
109        )
110
111        female_df = top_names_for_year(gender="F")
112        pm_top_female = tc.build_presentation_model(
113            df=female_df,
114            output_format="html",
115            data_value_func=klass_.data_value_func(female_df),
116            data_style_func=klass_.data_style_func(female_df),
117            header_value_func=klass_.header_value_func,
118            header_style_func=klass_.header_style_func,
119            index_style_func=klass_.index_style_func,
120            index_value_func=klass_.index_value_func,
121            index_name_func=lambda _: "Max by Year",
122        )
123
124        layout = [pm_all, [pm_top_female, pm_top_male]]
125        # render to xlsx
126        html = htmlw.HTMLWriter.to_html(layout, border=1, orientation="horizontal")
127        output_fp = os.path.join(tempfile.gettempdir(), "example3.html")
128        print("Writing to =", output_fp)
129        with open(output_fp, "w") as f:
130            f.write(html)
131
132
_images/html_example3.png

Example 4 - DataFrames with Multi-hierarchical columns and indices

Demonstrates rendering dataframes with multi-hierarchical indices and mult-hierarchical columns

  1class HTMLExample4:
  2    """
  3    Demonstrate styling and rendering of multi-hierarchical indexed dataframe
  4    into a html file.
  5    """
  6
  7    @staticmethod
  8    def data_value_func(df):
  9        def _inner(idx, col):
 10            if col == "gender":
 11                if df.loc[idx, col] == "F":
 12                    return "Female"
 13                return "Male"
 14            return df.loc[idx, col]
 15
 16        return _inner
 17
 18    @staticmethod
 19    def data_style_func(df):
 20        def _inner(idx, col):
 21            color = "#FFFFFF"
 22            text_align = "left"
 23            if col == "count":
 24                text_align = "right"
 25            if idx[1] == "F":
 26                color = "#bbdef8"
 27            else:
 28                color = "#e3f2fd"
 29
 30            return html_style.td_style(
 31                text_align=text_align,
 32                background_color=color,
 33                color="#000000",
 34                font_weight="normal",
 35                white_space="pre",
 36                padding="10px",
 37                border=None,
 38            )
 39
 40        return _inner
 41
 42    @staticmethod
 43    def index_name_value_func(value):
 44        return "Max By Year"
 45
 46    @staticmethod
 47    def header_value_func(node):
 48        return node.value.capitalize()
 49
 50    @staticmethod
 51    def header_style_func(node):
 52        return html_style.td_style(
 53            text_align="center",
 54            background_color="#4F81BD",
 55            color="#FFFFFF",
 56            font_weight="bold",
 57            white_space="pre",
 58            padding="10px",
 59            border=1,
 60        )
 61
 62    @staticmethod
 63    def index_value_func(node):
 64        if isinstance(node.value, str):
 65            return node.value.capitalize()
 66        return node.value
 67
 68    @staticmethod
 69    def index_style_func(node):
 70        return html_style.td_style(
 71            text_align="center",
 72            background_color="#4F81BD",
 73            color="#FFFFFF",
 74            font_weight="bold",
 75            white_space="pre",
 76            padding="10px",
 77            border=1,
 78        )
 79
 80    @classmethod
 81    def render_html(cls):
 82
 83        # Prepare first data frame (same as in render_xlsx)
 84        data_df = load_names_data()
 85        data_df = data_df[data_df["year"] >= 2000]
 86        g = data_df.groupby(("year", "gender"))
 87        df = g.max()
 88
 89        klass_ = cls
 90        pm = tc.build_presentation_model(
 91            df=df,
 92            output_format="html",
 93            data_value_func=klass_.data_value_func(df),
 94            data_style_func=klass_.data_style_func(df),
 95            header_value_func=klass_.header_value_func,
 96            header_style_func=klass_.header_style_func,
 97            index_style_func=klass_.index_style_func,
 98            index_value_func=klass_.index_value_func,
 99            index_name_func=klass_.index_name_value_func,
100        )
101
102        layout = [pm]
103        # render to xlsx
104        html = htmlw.HTMLWriter.to_html(layout, border=1)
105        output_fp = os.path.join(tempfile.gettempdir(), "example4.html")
106        print("Writing to =", output_fp)
107        with open(output_fp, "w") as f:
108            f.write(html)
109
110
_images/html_example4.png