使用pandas.to_html时怎么自定义表格样式

一、通过标签名设置css样式

使用pd.to_html()方法如果不指定文件路径,该函数会返回一个格式化的html字符串,我们可以对这个字符串进行自定义操作,比如直接用我们设置的css样式加上这个格式化的html,就可以实现自定义表格样式,如下:

data = {"姓名": ["张三", "李四", "王五"], "年龄": [28, 24, 22], "城市": ["北京", "上海青浦区", "广州"]}

df = pd.DataFrame(data)

# 使用自定义边框样式将DataFrame转换为HTML
custom_css = """
<style>
table {
    text-align: center;
    border-collapse: collapse;
    border: 2px dashed blue;
}
table th, table td {
    border: 2px dashed blue;
    padding: 8px;
}
</style>
"""

html_table = df.to_html(index=False, justify="center")

# 将自定义的CSS和HTML表格组合在一起
full_html = custom_css + html_table

# 打印或保存具有自定义边框样式的HTML表格
# print(full_html)
with open(r"C:\测试.html", "w", encoding="utf-8") as f:
    f.write(full_html)

效果如下:

二、通过class选择器设置css样式

pd.to_html()方法生成html字符串时会自动添加一个名为dataframeclass类选择器,如下:

<table border="1" class="dataframe">
  <thead>...</thead>
  <tbody>...</tbody>
</table>

使用默认类选择器设置样式

data = {"姓名": ["张三", "李四", "王五"], "年龄": [28, 24, 22], "城市": ["北京", "上海青浦区", "广州"]}

df = pd.DataFrame(data)

# 使用自定义边框样式
custom_css = """
<style>
.dataframe {
    text-align: center;
    border-collapse: collapse;
    border: 2px dashed blue;
}
.dataframe th, .dataframe td {
    border: 2px dashed blue;
    padding: 8px;
}
</style>
"""

html_table = df.to_html(index=False, justify="center")

# 将自定义的CSS和HTML表格组合在一起
full_html = custom_css + html_table

# # 打印或保存具有自定义边框样式的HTML表格
# print(full_html)
with open(r"C:\测试.html", "w", encoding="utf-8") as f:
    f.write(full_html)

使用自定义类选择器设置样式

需要指定参数classes,该参数会在html代码中自动添加一个class类选择器,如下:

df.to_html(classes="custom-table")
<table border="1" class="dataframe custom-table">
  <thead>...</thead>
  <tbody>...</tbody>
</table>

如此就可以通过自定义类名实现样式设置,如下示例:

data = {"姓名": ["张三", "李四", "王五"], "年龄": [28, 24, 22], "城市": ["北京", "上海青浦区", "广州"]}

df = pd.DataFrame(data)

# 使用自定义边框样式将DataFrame转换为HTML
custom_css = """
<style>
.custom-table {
    text-align: center;
    border-collapse: collapse;
    border: 2px dashed blue;
}
.custom-table th, .custom-table td {
    border: 2px dashed blue;
    padding: 8px;
}
</style>
"""

html_table = df.to_html(classes="custom-table", index=False, justify="center")

# 将自定义的CSS和HTML表格组合在一起
full_html = custom_css + html_table

# # 打印或保存具有自定义边框样式的HTML表格
# print(full_html)
with open(r"C:\测试.html", "w", encoding="utf-8") as f:
    f.write(full_html)
posted @ 2023-07-25 16:58  cnblogs用户  阅读(523)  评论(0编辑  收藏  举报