Skip to content

Instantly share code, notes, and snippets.

@drchaos
Last active July 14, 2017 13:18
Show Gist options
  • Save drchaos/59fa713573fa83533bad9e9d83f49849 to your computer and use it in GitHub Desktop.
Save drchaos/59fa713573fa83533bad9e9d83f49849 to your computer and use it in GitHub Desktop.
package main
import (
"encoding/csv"
"fmt"
"golang.org/x/text/encoding/charmap"
"golang.org/x/text/transform"
"html/template"
"io"
"log"
"os"
)
type Table struct {
Header []string
Rows [][]string
}
func NewTable(records [][]string) (tbl *Table, err error) {
tbl = new(Table)
if len(records) < 1 {
return nil, fmt.Errorf("Too few records in a table.")
}
tbl.Header = records[0]
if len(records) > 1 {
tbl.Rows = records[1:]
}
return
}
func (tbl *Table) GenerateHtml(out io.Writer) (err error) {
const tpl = `
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<table>
<tr>{{range .Header}}<th>{{.}}</th>{{end}}</tr>
{{range .Rows}}<tr>{{range .}}<td>{{.}}</td>{{end}}</tr>
{{end}}
</table>
</body>
</html>`
t, err := template.New("webpage").Parse(tpl)
if err != nil {
return
}
err = t.Execute(out, tbl)
if err != nil {
return
}
return nil
}
func ReadCsv(in io.Reader) ([][]string, error) {
r := csv.NewReader(in)
return r.ReadAll()
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
input_path := "./data.csv"
output_path := "./data.html"
in, err := os.Open(input_path)
defer in.Close()
check(err)
out, err := os.Create(output_path)
defer out.Close()
check(err)
t_in := transform.NewReader(in, charmap.Windows1252.NewDecoder()) //-- Comment this line and look at the html file
records, err := ReadCsv(t_in)
check(err)
tbl, err := NewTable(records)
check(err)
err = tbl.GenerateHtml(out)
check(err)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment