How to convert a dataframe to html?

dataframe
#1

Hi,

The requirement is - Have a dataframe with some data and need to send this via email format (In the body not as Attachement)

Have tried to convert it to html
df.to_html()
but this didnt work.
the data has to be in the body of the email not as an Attachment.

Any help.

Thanks,
Sachin

0 Likes

#2

You can export it to csv, copy the file manually from excel and then paste it into mail…unless you’re trying to automate this. Then you’ll need to research something on those lines.

0 Likes

#3

If you created HTML file with df.to_html() then open this file in any text editor, select what you need (probably from <table> to </table>), copy to clipboard (Ctrl+C), go to email and paste it from clipboard (Ctrl+V)

But I see few problems:

  1. I don’t know if <table></table> will be enough. But I’m sure you don’t need all tags from HTML. You don’t need <html>, <head>, <body>
  2. emailing application may not have function to put raw HTML. It may thread it as plain text.
  3. emailing application may not respect all HTML tags and it can remove some of tags. But rather it shouldn’t remove <table> element.
0 Likes

#4

You may try something like this -

import pandas as pd
import numpy as np

HEADER = ‘’’

</head>
<body>

‘’’
FOOTER = ‘’’

'''

test_csv=pd.read_csv(“C:\test.csv”)

with open(‘C:\test.html’, ‘w’) as f:
f.write(HEADER)
f.write(test_csv.to_html(classes=‘table’,index=False,escape=False))
f.write(FOOTER)

filename = “C:\test.csv”
f = file(filename)
attachment = MIMEText(f.read(),‘html’)
msg.attach(attachment)

0 Likes