Go 使用反射匯出 Excel

pibigstar發表於2019-09-30
type Record struct {
    Name string `xlsx:"A-姓名"`
    Age  int32  `xlsx:"B-年齡"`
}
func RefactorWrite(records []*Record) {
    xlsx := excelize.NewFile()
    index := xlsx.NewSheet("Sheet1")

    for i, t := range records {
        d := reflect.TypeOf(t).Elem()
        for j := 0; j < d.NumField(); j++ {
            // 設定表頭
            if i == 0 {
                column := strings.Split(d.Field(j).Tag.Get("xlsx"), "-")[0]
                name := strings.Split(d.Field(j).Tag.Get("xlsx"), "-")[1]
                xlsx.SetCellValue("Sheet1", fmt.Sprintf("%s%d", column, i+1), name)
            }
            // 設定內容
            column := strings.Split(d.Field(j).Tag.Get("xlsx"), "-")[0]
            switch d.Field(j).Type.String() {
            case "string":
                xlsx.SetCellValue("Sheet1", fmt.Sprintf("%s%d", column, i+2), reflect.ValueOf(t).Elem().Field(j).String())
            case "int32":
                xlsx.SetCellValue("Sheet1", fmt.Sprintf("%s%d", column, i+2), reflect.ValueOf(t).Elem().Field(j).Int())
            case "int64":
                xlsx.SetCellValue("Sheet1", fmt.Sprintf("%s%d", column, i+2), reflect.ValueOf(t).Elem().Field(j).Int())
            case "bool":
                xlsx.SetCellValue("Sheet1", fmt.Sprintf("%s%d", column, i+2), reflect.ValueOf(t).Elem().Field(j).Bool())
            case "float32":
                xlsx.SetCellValue("Sheet1", fmt.Sprintf("%s%d", column, i+2), reflect.ValueOf(t).Elem().Field(j).Float())
            case "float64":
                xlsx.SetCellValue("Sheet1", fmt.Sprintf("%s%d", column, i+2), reflect.ValueOf(t).Elem().Field(j).Float())
            }
        }
    }

    xlsx.SetActiveSheet(index)
    // 儲存到xlsx中
    err := xlsx.SaveAs("test_write.xlsx")
    if err != nil {
        fmt.Println(err)
    }
}
func main() {
    var records []*Record\
    records = append(records, &Record{\
       Name: "小明",\
      Age:  11,\
    })\
    records = append(records, &Record{\
       Name: "小華",\
      Age:  12,\
    })\
    // 反射寫\
    RefactorWrite(records)
}

相關文章