Thursday, April 30, 2009

Converting CSV file to HTML file by using VIM

I wrote a small VIM script to convert CSV file to HTML file.

You can get it from http://www.tnsatish.com/software/csvtohtml.vim

Usage is : vim -s csvtohtml.vim <filename>


After running the above command, the file will contain html code in place of CSV. This script will not work, if there are new lines or commas in any cell.

First row will be taken as header, and the color for that is ff80ff. For all the remaining rows, the color would be changed alternatively (b0ffff and ffff80). You can change the corresponding colors in the script (for bgcolor in tr tag), and the html would be created with the colors given.


Contents of csvtohtml.vim

:%s/^/<tr><td>/g
:%s/\//<br>/g
:%s/$/<\/td><\/tr>/g
:%s/,/<\/td><td>/g
:%s/<td><\/td>/<td>&nbsp;<\/td>/g
:%s/\n/X1X2X3X4X5X6/g
:%s/X1X2X3X4X5X6\(.\{-}\)X1X2X3X4X5X6/X1X2X3X4X5X6\1\r/g
:%s/<tr>/<tr bgcolor="#b0ffff">/
:%s/<tr>/<tr bgcolor="#ffff80">/
:%s/X1X2X3X4X5X6/\r/g
:1 s/bgcolor="[^"]*"/bgcolor="#ff80ff"/
:1 s/^/<table>\r/
:$ s/$/\r<\/table>/
:wq


I have used the above script to create the tables for MLA and MP Contestants at www.tnsatish.com and news.loksatta.org.

1 comment:

  1. hi dear!!!!!!!!!!!
    you can easily convert the CSV data into the HTML using the http://codebeautify.org/csv-to-html

    ReplyDelete