Create a nice html table from Excel with Python and Pandas

With this code you will be asked to open an Excel file and you will get a nice responsive table in an html file, ready to be put on your web page, without wasting any time.

All this with the help of Pandas (if you do not have it, go to the cmd and type pip install pandas) and some css style. This is the code to do it.

import pandas as pd
import os
from tkinter import Tk
from tkinter.filedialog import askopenfilename

Tk().withdraw()
filename = askopenfilename(initialdir=".")

table_class = "rwd-table"

html = """<style> table {border-collapse: collapse; width: 100%; } th, td {text-align: left; padding: 8px; } tr:nth-child(even) {background-color: #f2f2f2;} </style>"""
html += """
<script>
  window.console = window.console || function(t) {};
</script>
<script>
  if (document.location.search.match(/type=embed/gi)) {
    window.parent.postMessage("resize", "*");
  }
</script>"""



df = pd.read_excel(filename)
df.to_html("data.html")
with open("data.html") as file:
    file = file.read()
file = file.replace("<table ", "<table class=\"" + table_class + "\" ")
with open("data.html", "w") as file_to_write:
    file_to_write.write(html + file)
os.startfile("data.html")

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.