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 { padding: 5px; } .mystyle tr:nth-child(even) { background: #E0E0E0; } .mystyle tr:hover { background: silver; cursor: pointer; } ''' |
那么我怎样才能在下面的代码中实现
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) 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) |
您无需为此创建 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 { 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) ... |