go使用excelize导出xls
package excel import ( "bytes" "fmt" "github.com/kataras/iris/v12" "github.com/xuri/excelize/v2" "net/url" "reflect" "strconv" ) // DownExcelFile 下载excel文件 func DownExcelFile(ctx iris.Context, fileName string, bt *bytes.Buffer) { //设置文件类型 ctx.Header("Content-Type", "application/vnd.ms-excel;charset=utf8") //设置文件名称 ctx.Header("Content-Disposition", "attachment; filename="+url.QueryEscape(fileName)) _, _ = ctx.Write(bt.Bytes()) } // WriteExcel 写入excel func WriteExcel(data []interface{}, sheetName string) (*bytes.Buffer, error) { f := excelize.NewFile() f.SetSheetName("Sheet1", sheetName) rowNum := 1 //保存内容 for i, u1 := range data { //读取结构体 p1 := reflect.TypeOf(u1) if i == 0 { fmt.Println(p1.String()) //设置表头 header := make([]string, 0) for j := 0; j < p1.NumField(); j++ { key := p1.Field(j) fmt.Println("name=", key.Name, ",tag=", key.Tag.Get("xlsx")) xlsxTag := key.Tag.Get("xlsx") if xlsxTag != "" { header = append(header, xlsxTag) } } f.SetSheetRow(sheetName, "A1", &header) } //读取值 v1 := reflect.ValueOf(u1) sp1 := make([]interface{}, 0) for l := 0; l < p1.NumField(); l++ { key := p1.Field(l) xlsxTag := key.Tag.Get("xlsx") if xlsxTag != "" { val := v1.Field(l).Interface() sp1 = append(sp1, val) } } rowNum++ f.SetSheetRow(sheetName, "A"+strconv.Itoa(rowNum), &sp1) } return f.WriteToBuffer() } // WriteExcelHeader 设置excel表头 func WriteExcelHeader(data interface{}, sheetName string) (*bytes.Buffer, error) { f := excelize.NewFile() f.SetSheetName("Sheet1", sheetName) p1 := reflect.TypeOf(data) //设置表头 header := make([]string, 0) for j := 0; j < p1.NumField(); j++ { key := p1.Field(j) fmt.Println("name=", key.Name, ",tag=", key.Tag.Get("xlsx")) xlsxTag := key.Tag.Get("xlsx") if xlsxTag != "" { header = append(header, xlsxTag) } } f.SetSheetRow(sheetName, "A1", &header) return f.WriteToBuffer() }