go get github.com/KarlTango/xs
- github.com/tealeg/xlsx
If you wan to get message from a excel file like this:
(Excel could be found in example folder).
You could define struct with xs tag to map struct key excel column name
type User struct {
Username string `xs:"Username"`
Age int `xs:"Age"`
Sex string `xs:"Sex"`
}
and then you can use UnmarshalFromFile
var users = make([]User, 0)
filePath := "example/test.xlsx"
err := UnmarshalFromFile(filePath, &users)
or use Unmarshal
var users = make([]User, 0)
filePath := "example/test.xlsx"
body, _ := ioutil.ReadFile(filePath)
err = Unmarshal(body, &users)
The other way round, if you want to write a excel from go struct slice, you can use Marshal
type User struct {
Username string `xs:"Username"`
Age int `xs:"Age"`
Sex string `xs:"Sex"`
}
type User2 struct {
Username string `xs:"Username"`
Salary float64 `xs:"Salary"`
}
users := []User{{"Karl", 25, "Male"}, {"Ann", 18, "Female"}}
users2 := []User2{{"Karl", 8000.00}, {"Ann", 9999.50}}
//marshal
body, err := Marshal(users, users2)
if err != nil {
//TODO: process err
}
//write file
err = ioutil.WriteFile("user.xlsx", body, 06666)
if err != nil {
//TODO: process err
}