0

It's possible to create HTML page from a CSV file, with the following:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

df = pd.read_csv('../data.csv',delimiter=';', engine='python')
df.to_html('csv.html')

I would like to make that HTML to respect some CSS present in csv.css. One way to get this is to manually edit csv.html head, inserting:

<head><link rel="stylesheet" type="text/css" href="csv.css"></head> 

Instead of doing it manually, how one can get there programmatically (using Python)?

KcFnMi
  • 5,516
  • 10
  • 62
  • 136
  • can you get some idea from this accepted SO here - http://stackoverflow.com/questions/18876022/how-to-format-ipython-html-display-of-pandas-dataframe – Nikhil Nanjappa Oct 12 '16 at 08:42

1 Answers1

1

The to_html method does not output an entire HTML document. Instead, it just creates a single table element.

If you want to include CSS, you have to create additional HTML elements, and insert them yourself before writing the data. One of the simplest ways is as follows:

with open('test.html', 'w') as fobj:
    fobj.write('<html><head><link rel="stylesheet" href="test.css"></head><body>')
    df.to_html(fobj)
    fobj.write('</body></html>')

The first argument of to_html has to be a file-like object: so it can be either a file object as in the above example or a StringIO.

rubik
  • 8,814
  • 9
  • 58
  • 88