24

我一直在关注pandas 的风格指南,它工作得很好。

如何通过 Outlook 使用 to_html 命令保留这些样式?文档对我来说似乎有点缺乏。

(df.style
   .format(percent)
   .applymap(color_negative_red, subset=['col1', 'col2'])
   .set_properties(**{'font-size': '9pt', 'font-family': 'Calibri'})
   .bar(subset=['col4', 'col5'], color='lightblue'))

import win32com.client as win32
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.Subject = subject_name
mail.HTMLbody = ('<html><body><p><body style="font-size:11pt; 
font-family:Calibri">Hello,</p> + '<p>Title of Data</p>' + df.to_html(
            index=False, classes=????????) '</body></html>')
mail.send

to_html 文档显示,我可以将一个 classes 命令放在 to_html 方法中,但我无法弄清楚。我的数据框似乎也没有我在顶部指定的样式。

如果我尝试:

 df = (df.style
       .format(percent)
       .applymap(color_negative_red, subset=['col1', 'col2'])
       .set_properties(**{'font-size': '9pt', 'font-family': 'Calibri'})
       .bar(subset=['col4', 'col5'], color='lightblue'))

那么 df 现在是一个 Style 对象,你不能使用 to_html。

编辑 - 这是我目前正在做的修改我的表格。这行得通,但我无法保留 pandas 提供的 .style 方法的酷特性。

email_paragraph = """
<body style= "font-size:11pt; font-family:Calibri; text-align:left; margin: 0px auto" >
"""

email_caption = """
<body style= "font-size:10pt; font-family:Century Gothic; text-align:center; margin: 0px auto" >
"""


email_style = '''<style type="text/css" media="screen" style="width:100%">
    table, th, td {border: 0px solid black;  background-color: #eee; padding: 10px;}
    th {background-color: #C6E2FF; color:black; font-family: Tahoma;font-size : 13; text-align: center;}
    td {background-color: #fff; padding: 10px; font-family: Calibri; font-size : 12; text-align: center;}
  </style>'''
4

3 回答 3

44

一旦你添加style到你的链式分配中,你就在一个Styler对象上进行操作。该对象具有render将 html 作为字符串获取的方法。因此,在您的示例中,您可以执行以下操作:

html = (
    df.style
    .format(percent)
    .applymap(color_negative_red, subset=['col1', 'col2'])
    .set_properties(**{'font-size': '9pt', 'font-family': 'Calibri'})
    .bar(subset=['col4', 'col5'], color='lightblue')
    .render()
)

然后将 包含html在您的电子邮件中,而不是df.to_html().

于 2016-06-11T04:59:55.377 回答
3

这不是一个奢侈/pythonic 的解决方案。我在 to_html() 方法生成的 html 代码之前插入了指向直接 css 文件的链接,然后将整个字符串保存为 html 文件。这对我来说效果很好。

dphtml = r'<link rel="stylesheet" type="text/css" media="screen" href="css-table.css" />' + '\n'
dphtml += dp.to_html()

with open('datatable.html','w') as f:
    f.write(dphtml)
于 2017-05-02T13:14:51.460 回答
0

选择表格(jupyter 中呈现的、样式化的、数据框小部件)并复制粘贴到电子邮件正文对我有用(使用 Outlook Office)。

没有手动 html 提取、保存、加载或类似的东西。

于 2020-10-21T10:03:13.980 回答