```
package main
import (
"fmt"
"github.com/tealeg/xlsx"
)
type Member struct {
Name string `xlsx:"0"`
Age int `xlsx:"1"`
}
func main() {
WriteToXlsx()
ReadXlsx()
}
//把Member结构的数据写入到.xlsx文件当中
func WriteToXlsx() {
var file *xlsx.File
var sheet *xlsx.Sheet
var row *xlsx.Row
var err error
file = xlsx.NewFile()
sheet, err = file.AddSheet("Sheet1")
if err != nil {
fmt.Printf(err.Error())
}
row = sheet.AddRow()
member := &Member{"A1", 21}
a := row.WriteStruct(member, -1)
fmt.Println(a)
file.Save("MyXLSXFile.xlsx")
}
//把.xlsx文件的内容读取到Member结构体中.
func ReadXlsx() {
xlFile, err := xlsx.OpenFile("MyXLSXFile.xlsx")
if err != nil {
fmt.Println("err:", err)
}
members := make([]Member, 0)
member := new(Member)
length := xlFile.Sheet["Sheet1"].MaxRow
for i := 0; i < length; i++ {
xlFile.Sheet["Sheet1"].Rows[i].ReadStruct(member)
if err != nil {
fmt.Println("err:", err)
break
}
members = append(members, *member)
}
fmt.Println("members:", members)
}
```
推荐一个功能丰富、兼容性好、高性能的 Excel 文档基础库:[https://github.com/xuri/excelize](https://github.com/xuri/excelize)
#1