go excelize 批量写入数据到Excel
func CreateXlS(data [][]string, fileName string, headerNameArray []string) {
f := excelize.NewFile()
sheetName := "sheet1"
sheetWords := []string{
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U",
"V", "W", "X", "Y", "Z",
}
for k, v := range headerNameArray {
f.SetCellValue(sheetName, sheetWords[k]+"1", v)
}
//设置列的宽度
f.SetColWidth("Sheet1", "A", sheetWords[len(headerNameArray)-1], 18)
headStyleID, _ := f.NewStyle(`{
"font":{
"color":"#333333",
"bold":false,
"family":"arial"
},
"alignment":{
"vertical":"center",
"horizontal":"center"
}
}`)
//设置表头的样式
f.SetCellStyle(sheetName, "A1", sheetWords[len(headerNameArray)-1]+"1", headStyleID)
line := 1
// 循环写入数据
for _, v := range data {
line++
for kk, _ := range headerNameArray {
f.SetCellValue(sheetName, sheetWords[kk]+strconv.Itoa(line), v[kk])
}
}
// 保存文件
if err := f.SaveAs(fileName + ".xlsx"); err != nil {
fmt.Println(err)
}
}
---
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() }