louis
louis

Reputation: 625

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 PowerShell and store it into HTML file.

Upvotes: 0

Views: 18757

Answers (3)

Martin Brandl
Martin Brandl

Reputation: 59001

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 html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="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.

Upvotes: 4

Omar Omeiri
Omar Omeiri

Reputation: 1833

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!

Upvotes: 1

naveenkumar.s
naveenkumar.s

Reputation: 1001

This may help you:

 import sys
 import csv
 if len(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 contents

for row in reader: # Read a single row from the CSV file

 # write header row. assumes first row in csv contains header
   if rownum == 0:
      htmlfile.write('<tr>') # write <tr> tag
      for 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 shell
   print "Created " + str(rownum) + " row table."
   exit(0)

Upvotes: 2

Related Questions