Skip to content Skip to sidebar Skip to footer

Convert Csv To A Html Table Format And Store In A Html File

I have tried few shell scripts to convert to a HTML table format but I didnt get desired output. Could anyone help here to convert CSV to a HTML table format using Python or PowerS

Solution 1:

This is easy with PowerShell. You can use the ConvertFrom-Csv cmdlet to convert your csv to a object array and use the ConvertTo-Html cmdlet to convert it to a html table. To store the html, use the Set-Content cmdlet:

$myCsv = 
@'
Id, Name
1, Hello
2, World
'@

$myCsv | ConvertFrom-Csv | ConvertTo-Html | Set-Content -Path 'YOUR_PATH_HERE.csv'

Output:

<!DOCTYPE htmlPUBLIC"-//W3C//DTD XHTML 1.0 Strict//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><htmlxmlns="http://www.w3.org/1999/xhtml"><head><title>HTML TABLE</title></head><body><table><colgroup><col/><col/></colgroup><tr><th>Id</th><th>Name</th></tr><tr><td>1</td><td>Hello</td></tr><tr><td>2</td><td>World</td></tr></table></body></html>

Note: If you need to load the csv from a file, you can either use the Get-Content cmdlet to load it and convert it using the example above, or you can use the Import-Csv cmdlet.

Solution 2:

This may help you:

import sys
 import csv
 iflen(sys.argv) < 3:
    print"Usage: csvToTable.py csv_file html_file"
    exit(1)

 # Open the CSV file for reading

    reader = csv.reader(open(sys.argv[1]))

 # Create the HTML file for output

    htmlfile = open(sys.argv[2],"w")

 # initialize rownum variable
    rownum = 0# write <table> tag

   htmlfile.write('<table>')

 # generate table contentsfor row in reader: # Read a single row from the CSV file# write header row. assumes first row in csv contains headerif rownum == 0:
      htmlfile.write('<tr>') # write <tr> tagfor column in row:
          htmlfile.write('<th>' + column + '</th>')
      htmlfile.write('</tr>')

  #write all other rows else:
      htmlfile.write('<tr>')    
      for column in row:
          htmlfile.write('<td>' + column + '</td>')
      htmlfile.write('</tr>')

   #increment row count 
   rownum += 1# write </table> tag
   htmlfile.write('</table>')

 # print results to shellprint"Created " + str(rownum) + " row table."
   exit(0)

Solution 3:

well, I think that the easiest way to do it is.

import pandas as pd

csv = pd.read_csv('csv_file.csv')
html_table = csv.to_html()

f = open('html_file.html', 'w')
f.write(html_table)
f.close()

try it out!

Post a Comment for "Convert Csv To A Html Table Format And Store In A Html File"