首页 > 解决方案 > 将数据框从 Python 写入 html 时修复表头

问题描述

我试图headers在写我的时候修复我dataframe的 to HTML。我浏览了这个似乎有类似问题的链接 ,但这并没有真正帮助,因为我正在创建stylesin Python

这是我的工作代码

import numpy as np
import pandas as pd
from IPython.display import HTML


df.index = np.arange(1, len(df)+1)

def hover(hover_color="#FF5733"):
    return dict(selector="tbody tr:hover",
            props=[("background-color", "%s" % hover_color)])

styles = [
    #table properties
    dict(selector=" ", 
         props=[("margin","0"),
                ("font-family",'calibri'),
                ("border-collapse", "collapse"),
                ("border","none"),
                ("border", "2px solid #ccf")
                   ]),

    #header color - optional
    dict(selector="thead", 
         props=[("background-color","#489AF3"),
               ("position", "sticky")
               ]),

    #background shading
    dict(selector="tbody tr:nth-child(even)",
         props=[("background-color", "#fff")]),
    dict(selector="tbody tr:nth-child(odd)",
         props=[("background-color", "#eee")]),

    #cell spacing
    dict(selector="td", 
         props=[("padding", ".5em"),
         ("overflow", "hiddeb"),
         ("text-overflow", "ellipsis")]),

    #header cell properties
    dict(selector="tblTitle", 
         props=[("font-size", "95%"),
                ("text-align", "center"),
                ("position", "sticky"),
                ("top", 0)]),

    #caption placement
    dict(selector="caption", 
         props=[("caption-side", "bottom")]),

     dict(selector="body_panel",
          props=[("display", "inline-block"),
          ("overflow-y", "scroll")]),

    #render hover last to override background-color
    hover()
]

# this forces grey background on header
styler = df.style.set_properties(**{'text-align': 'center'}).set_table_styles(styles)

# HTML string
html = styler.render()

# save html
with open('wwx.html', 'w') as f:
    f.write(html)

标签: pythonhtmlcsspython-3.xfixed-header-tables

解决方案


推荐阅读