go gin 返回csv文件

4,177 阅读1分钟

func CompanyDownload(c *gin.Context) {
	var (
		err         error
		outCompanys []*OutCompany
		headList    []string
		dataBytes   = new(bytes.Buffer)
	)

	err = mysql.Instance().Select(&outCompanys, `select
	c.id, if(c.short_name="", c.title, c.short_name) as title,
	(select count(1) from recruiter where company_id=c.id) as hr_count,
	(select count(1) from job where company_id=c.id) as total,
	(select count(1) from job where status=1 and company_id=c.id) as online_count,
	(select count(1) from user_apply u where u.job in (select j.id from job j where j.recruiter_id!=0 and j.company_id=c.id)) as apply_count,
	(select count(1) from user_apply u where u.job in (select j.id from job j where j.recruiter_id=0 and j.company_id=c.id)) as spider_count
	from company c order by online_count desc`)
	if err != nil {
		if err == sql.ErrNoRows {
			api400(c, "not select data")
			xlog.Info("not select data :%v", err)
			return
		}
		api501(c)
		xlog.Err(err)
		return
	}
	headList = []string{"ID", "Company", "HR", "Total Jobs", "Online Jobs", "Apply", "爬虫/应聘"}
	//设置编码格式
	dataBytes.WriteString("\xEF\xBB\xBF")
	wr := csv.NewWriter(dataBytes)
	wr.Write(headList)
	for _, company := range outCompanys {
		bodyList := []string{
			company.ID,
			company.Title,
			strconv.Itoa(company.HrCount),
			strconv.Itoa(company.Total),
			strconv.Itoa(company.OnlineCount),
			strconv.Itoa(company.ApplyCount),
			strconv.Itoa(company.SpiderCount),
		}
		wr.Write(bodyList)
	}
        //清空
	wr.Flush()
	c.Writer.Header().Set("Content-type", "application/octet-stream")
	//c.Writer.Header().Set("Content-Type", "text/csv")
	c.Writer.Header().Set("Content-Disposition", fmt.Sprintf("attachment;filename=%s", "companys.csv"))
	c.String(200, dataBytes.String())
}