github.com/cuishu/excel 是用来辅助操作xlsx文件的库,实现了xlsx文件和go对象的映射,使操作xlsx文件如同操作go对象一样简单。

依赖 github.com/360EntSecGroup-Skylar/excelize/v2

获取 excel

go get github.com/cuishu/excel

使用方法

excel文件的第一行必须和Go struct的tag一致

For example

a.xlsx

Sheet1结构如下

id name
1 Smith
type Human {
    ID   int    `xlsx:"id"`
    Name string `xlsx:"name"`
}

读取 Sheet

var humans []Human
Sheet{Filename: "a.xlsx", Sheet: "Sheet1"}.Scan(&humans)
for _, human := range humans {
  fmt.Println(human.Name)
  ...
}

将go slice 写入excel文件

var humans []Human
humans = append(Human{ID: 1, Name: "Smith"})
humans = append(Human{ID: 2, Name: "Jack"})
humans = append(Human{ID: 3, Name: "James"})
    
buff, err := (&Sheet{Sheet: "Sheet1"}).Export(&users)
ioutil.WriteFile("a.xlsx", buff.Bytes(), 0644)

支持的数据类型

int int8 int16 int32 int64
uint uint8 uint16 uint32 uint64
float32 float64
string
bool

映射整个excel文件

如果文件有不止一个Sheet,应该使用一个结构来映射它们。

type Human struct {
    ID   int    `xlsx:"id"`
    Name string `xlsx:"name"`
}
type Animal Human
type Example struct {
    Humans  []Human  `xlsx:"humans"`
    Animals []Animal `xlsx:"animals"`
}
var example Example
// 读
(Excel{Filename: "b.xlsx"}).Scan(&example)
// 写入 bytes buffer
Excel{}.Export(&example)

高级用法

您可以使用自定义类型来实现 MarshalXLSX 和 UnmarshalXLSX 来实现类型转换。

const (
    Male = 1
    Female = 2
)
type Sex int
func (sex Sex) MarshalXLSX() ([]byte, error) {
    if sex == Male {
        return []byte("Male"), nil
    } else if sex == Female {
        return []byte("Female"), nil
    }
    return nil, errors.New("invalid value")
}
func (sex *Sex) UnmarshalXLSX(data []byte) error {
    s := string(data)
    if s == "Male" {
        *sex = Male
        return nil
    }
    if s == "Female" {
        *sex = Female
        return nil
    }
    return errors.New("invalid value")
}