16 August 2021

export pandas dataframe to html and appy css styles

 export pandas dataframe to html and appy css styles

 

 Ku Tang Pan

I found the most precise, and frankly the easiest way of doing it is skipping the styling, to_html() etc. and converting the DF to a dictionary using the df.to_dict() method.

Specifically what gave me trouble, was displaying the styled pandas html in an outlook email, as it just wouldn't render properly with the css mess that pandas was producing.

iterate over the dict and generate the html there by simply wrapping keys/values in the tags that you need, adding classes etc. and concatenate this all into one string. Then paste this str into a prepared template with a predefined css.

For convenience I found it's useful to export the same df twice, using .to_dict() and to_dict('index') to first fill in the columns and then work your way down row by row. Alternatively just have a list of relevant column names.

dict_data = [df.to_dict(), df.to_dict('index')]

return_str = '<table><tr>'

for key in dict_data[0].keys():
    return_str = return_str + '<th class="header">' + key + '</th>'

return_str = return_str + '</tr>'

for key in dict_data[1].keys():
    return_str = return_str + '<tr><th class="index">' + key + '</th>'
    for subkey in dict_data[1][key]:
        return_str = return_str + '<td>' + dict_data[1][key][subkey] + '</td>'

return_str = return_str + '</tr></table>'

and then return_str goes into the template.

 

No comments:

Post a Comment