gin中文件流导出excel
func GoodsExport(c *gin.Context) { var list []GoodsExports dbMysql := mysql.GetORM() sql := `select goods_id,user_id,goods_name from tb_goods` dbMysql.SQL(sql).Find(&list) //导出 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() row.AddCell().Value = "商品ID" row.AddCell().Value = "用户" row.AddCell().Value = "商品标题" for _, v := range list { row = sheet.AddRow() row.AddCell().Value = strconv.Itoa(v.GoodsId) row.AddCell().Value = v.UserId row.AddCell().Value = v.GoodsName } buf := new(bytes.Buffer) err = file.Write(buf) if err != nil { fmt.Printf(err.Error()) return } c.Header("Content-Description", "File Transfer") c.Header("Content-Disposition", "attachment; filename=商品.xlsx") c.Data(http.StatusOK, "text/xlsx", buf.Bytes()) }
导出csv
1 func makeCsv(fileName string, data [][]string) string { 2 fileName += ".csv" 3 filePath := "./static/" + fileName 4 fp, err := os.Create(filePath) // 创建文件句柄 5 err_handle.CheckErr(err) 6 7 defer fp.Close() 8 fp.WriteString("xEFxBBxBF") // 写入UTF-8 BOM 9 w := csv.NewWriter(fp) //创建一个新的写入文件流 10 w.WriteAll(data) 11 w.Flush() 12 return fileName 13 }