Home > Back-end >  Create a html table with style from csv
Create a html table with style from csv

Time:05-16

I am trying to create an html table from a csv file. In the csv file I have the three fields that are already filtered so that it does not generate problems, but when I run the code, the report file does not generate any output and it must be an error when going through the file or I do not know where else is the failure:

awk '
BEGIN {
  FS = ","
  header()
  i=0
}

function header(){
print "<!DOCTYPE html>\n<head><title>Report</title>"
print "<link rel=\047stylesheet\047 href=\047style.css\047>"
print "<meta charset=\047utf-8\047/>" 
print "</head>\n<body>\n<div class=\047head-style\047<h2>Report</h2>\n</div>"
print "<table>\n<tr><th>Platan</th><th>Recl</th><th>Tror</th>"
}

function print_line(Platan,Recl,Tror){
  printf("%s %.2f %s %.2f %s", "<tr><td>"Platan"</td><td>",Recl,"</td><td>", Tror, "</td></tr>") ;
}

function footer(){
print "</table>\n<div class=\047footer\047>\n<p>0000 st</p>\n</div>\n</body>\n</html>"
}


{
  if (NR>1){
    print_line()
  }
}

END{}
footer()
}' rm.csv > rep.html

The csv input looks similar to this:

Platan,Recl,Tror
SA,Cele,11
SA,Serale,34
RE,Cele,23
LE,Serale,2
ME,Cele,14
ME,Serale,32

CodePudding user response:

I cannot see an obvious error in your file but was able to generate the required html file using an awk script file as follows (the correct #! path can be found using which awk in terminal):

#! /usr/bin/awk -f


BEGIN {
FS =","
print "<!DOCTYPE html>\n<head><title>Report</title>"
print "<link rel=\"stylesheet\" href=\"style.css\">"
print "<meta charset=\"utf-8\"/>" 
print "</head>\n<body>\n<div class=\"head-style\"<h2>Report</h2>\n</div>"

}

NR<2 {
print "<table>\n<tr><th>"$1"</th><th>"$2"</th><th>"$3"</th>"
}

NR>1 {
print "<tr><td>"$1"</td><td>"$2"</td><td>"$3"</td></tr>"
}

END {
print "</table>\n<div class=\"footer\">\n<p>0000 st</p>\n</div>\n</body>\n</html>"
}

I formatted the printing using field references $1 etc. between quotted string. Note also, quotes can be escaped for printing.

I saved the script as awkScript.awk and made it executable from the command line using:

chmod  x awkScript.awk

This can then be executed on the csv file with the command:

./awkScript.awk rm.csv > rep.html

CodePudding user response:

It looks like you forgot to pass the fields as parameters to function print_line(Platan, Recl, Tror).

# Since "Platan" and "Recl" are strings, I think the format string
# should be: "%s %s %.2f %s\n" (BTW, I included "\n" to improve readability).

function print_line(Platan, Recl, Tror)``` 
  printf("%s %s %.2f %s\n", "<tr><td>"Platan"</td>", "<td>"Recl"</td><td>", Tror, "</td></tr>") ;
}

{
  if (NR>1){
    print_line($1, $2, $3)   # should solve
  }
}
  • Related