How to apply CSS class (my style) to Pandas DataFrame using to_html
抱歉,我是 HTML 和 CSS 新手。
目标是从数据框创建 HTML 表格并通过电子邮件发送。
但是我怎样才能使输出表变得时尚呢?
让我想要不同的背景标题、字体等?
这是我要实现的样式:
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
mystyle = ”’ .mystyle { font-size: 11pt; font-family: Arial; border-collapse: collapse; border: 1px solid silver; } .mystyle td, th { .mystyle tr:nth-child(even) { .mystyle tr:hover { ”’ |
那么我怎样才能在下面的代码中实现
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
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) df = pd.DataFrame({ |
您无需为此创建 css 文件。如果将它们连接到字符串,一切都可以正常工作。这是我通常的做法:
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
message_start = f""" <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> Report for {date}""" 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 { #customers tr:nth-child(even){background-color: #f2f2f2;} #customers tr:hover {background-color: #ddd;} #customers th { 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) … |
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/268015.html