Created
December 7, 2017 03:30
-
-
Save jszwec/89465a89731a9bd9da215ffafa1ce412 to your computer and use it in GitHub Desktop.
main.go with csvutil for github.com/AppliedGo/spreadsheet Raw
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"encoding/csv" | |
"fmt" | |
"io" | |
"io/ioutil" | |
"log" | |
"os" | |
"github.com/jszwec/csvutil" | |
) | |
type Order struct { | |
Date string `csv:",omitempty"` | |
OrderID int `csv:"Order ID,omitempty"` | |
OrderItem string `csv:"Order Item,omitempty"` | |
UnitPrice Price `csv:"Unit Price,omitempty"` | |
Quantity int `csv:",omitempty"` | |
Total Price `csv:",omitempty"` | |
} | |
func main() { | |
f, err := os.Open("orders.csv") | |
if err != nil { | |
log.Fatal(err) | |
} | |
defer f.Close() | |
r := csv.NewReader(f) | |
r.ReuseRecord = true | |
r.Comma = ';' | |
dec, err := csvutil.NewDecoder(r) | |
if err != nil { | |
log.Fatal(err) | |
} | |
summary := Order{OrderItem: "Sum"} | |
pens := Order{OrderItem: "Ball Pens"} | |
var orders []Order | |
for { | |
var order Order | |
if err := dec.Decode(&order); err == io.EOF { | |
break | |
} else if err != nil { | |
log.Fatal(err) | |
} | |
order.Total = order.UnitPrice * Price(order.Quantity) | |
summary.Total += order.Total | |
if order.OrderItem == "Ball Pen" { | |
pens.Quantity += order.Quantity | |
} | |
orders = append(orders, order) | |
} | |
orders = append(orders, summary, pens) | |
b, err := csvutil.Marshal(orders) | |
if err != nil { | |
log.Fatal(err) | |
} | |
if err := ioutil.WriteFile("ordersReport.csv", b, 0666); err != nil { | |
log.Fatal(err) | |
} | |
} | |
type Price float64 | |
func (p *Price) UnmarshalCSV(data []byte) error { | |
_, err := fmt.Sscanf(string(data), "%f", p) | |
return err | |
} | |
func (p Price) MarshalCSV() ([]byte, error) { | |
if p == 0 { | |
return nil, nil | |
} | |
var buf bytes.Buffer | |
fmt.Fprintf(&buf, "%.2f", p) | |
return buf.Bytes(), nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment