python - 如何使用 to_html 将 CSS 类(我的风格)应用到 Pandas DataFrame

标签 python html css pandas dataframe

抱歉,我是 HTML 和 CSS 新手。

目标是从数据帧创建 HTML 表并通过电子邮件发送。

但是如何设计输出表呢? 我想要不同的背景标题、字体等吗?

这是我想要实现的样式:

mystyle = 
'''
.mystyle {
    font-size: 11pt; 
    font-family: Arial;
    border-collapse: collapse; 
    border: 1px solid silver;

}

.mystyle td, th {
    padding: 5px;
}

.mystyle tr:nth-child(even) {
    background: #E0E0E0;
}

.mystyle tr:hover {
    background: silver;
    cursor: pointer;
}

'''

那么如何在下面的代码中实现 mystyle 并获得时尚的表格?我尝试了 df.to_html(classes=mystyle) 但没有成功

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import pandas as pd
import datetime as dt

yesterday = dt.datetime.now() - dt.timedelta(days=1)
date = "'" + yesterday.strftime('%m-%d-%Y') + "'"


df = pd.DataFrame({
                'Position': ['DBA','CEO','Underwriter']
                ,'Salary': [100000,300000,60000]
                ,'Posted':['2019-01-01', '2019-05-01', '2019-03-15']
                ,'Link': ['myjob.com','ceo.com','insurance.com']
                })
html = """\
<html>
  <head>Report for """ + date + """</head>
  <body>
    {0}
  </body>
</html>
""".format(df.to_html())
print(html)

enter image description here

最佳答案

您不需要为此创建 css 文件。如果将它们连接到字符串,一切都可以正常工作。我通常是这样做的:

message_start = f"""
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>Report for {date}</title>"""
message_style = """
  <style type="text/css" media="screen">
    #customers {
      font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
      font-size: 12px;
      border-collapse: collapse;
      width: 100%;
    }

    #customers td, #customers th {
      border: 1px solid #ddd;
      padding: 8px;
    }

    #customers tr:nth-child(even){background-color: #f2f2f2;}

    #customers tr:hover {background-color: #ddd;}

    #customers th {
      padding-top: 12px;
      padding-bottom: 12px;
      text-align: left;
      background-color: #4CAF50;
      color: white;
    }
  </style>
</head>
<body>
"""
message_body = df.to_html(index=False, table_id="customers") #set table_id to your css style name
message_end = """</body>"""
messages = (message_start + message_style + message_body + message_end)
part = MIMEText(messages, 'html')  # create MIMEText
msg.attach(part)  
...

关于python - 如何使用 to_html 将 CSS 类(我的风格)应用到 Pandas DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59882993/

相关文章:

jquery - 如何在 html/jquery 中存储值

html - php 输出中的内联 css

html - 如何缩放图像超出其原始尺寸

css - 当我聚焦/取消聚焦用户名时,密码输入会抖动

html - html 菜单项中的左对齐和右对齐文本

python - 测试 python 代码

python - python2.5中的Exception_Record问题

python - Numpy 将函数应用于选定的矩阵索引

python - django CMS 历史选项卡在哪里?

javascript - 仅更改 Framework7 中一个 radio 的非事件颜色?