Nickpick
Nickpick

Reputation: 6597

Simplest way to create a fancy javascript table from a pandas dataframe and embed it in a single html file

I'm looking for a way to create a fancy table (or in fact multiple tables) embedded in a single html file, that goes beyond what a normal pandas dataframe .to_html() can do.

It should have the following functions: - allows filtering (client side) - allows pivoting (client side) - has additional formatting options (e.g. ensuring numbers are right-aligned etc)

What's the simplest way to embed a javascript template into an html, that I can then feed with a serialized json produced by the pandas dataframe and embed it in a single file. Any recommendations would be greatly appreciated.

Upvotes: 1

Views: 2125

Answers (1)

Enigma Machine
Enigma Machine

Reputation: 153

Perhaps Simple-DataTables will be of use to you.

Here is a minimal example, which generates a working 'demo.htm' file:

import os
import pandas as pd
import numpy as np
import jinja2

# Project specific global variables: paths, URIs, etc.
file_abspath = os.path.abspath(__file__)
file_basename = os.path.basename(file_abspath)
file_dirname = os.path.dirname(file_abspath)


def main():
    """The main function."""
    os.chdir(file_dirname)

    # Create a random dataframe.
    df_cols = list('ABCD')
    row_count = 12
    df = pd.DataFrame(np.random.randint(0, 100, size=(
        row_count, len(df_cols))), columns=df_cols)

    # Generate HTML from template.
    template = jinja2.Template("""<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Demo</title>
    <link href="https://cdn.jsdelivr.net/npm/simple-datatables@latest/dist/style.css" rel="stylesheet" type="text/css">
    <script src="https://cdn.jsdelivr.net/npm/simple-datatables@latest" type="text/javascript"></script>
    </head>

    <body>

        {{ dataframe }}

    </body>

    <script defer type="text/javascript">
        let myTable = new simpleDatatables.DataTable("#myTable");
    </script>

</html>"""
                               )

    output_html = template.render(dataframe=df.to_html(table_id="myTable"))

    # Write generated HTML to file.
    with open("demo.htm", "w", encoding="utf-8") as file_obj:
        file_obj.write(output_html)


if __name__ == "__main__":
    main()


I hope this helps, but it may or may not provide all functionality you have asked for, one may need to check the datatables documentation for finer details.

Upvotes: 1

Related Questions