GoLang+gin框架导出Excel

作者: adm 分类: go 发布时间: 2022-09-05

安装

go get github.com/xuri/excelize/v2

控制器

func (e Users) UserExport(c *gin.Context) {
	srv := service.Users{}
	req := dto.SysUserPageList{}
	
	records := make([]model.SysUser, 0)

	content := srv.UserExport(&req, &records)
	fileName := fmt.Sprintf("%s%s%s.xlsx", time.Now().Format("2016-01-02"), `-`, "user")
	c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
	c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
	http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)

}

服务层

import 
 _ "image/gif"
    _ "image/jpeg"
    _ "image/png"
func (e *Users) UserExport(c *dto.SysUserPageList, records *[]model.SysUser) (reader *bytes.Reader) {

	err := e.Orm.Table(model.SysUser{}.TableName()).Find(records).Error
	if err != nil {
		return reader
	}
	return e.download(*records)

}

func (e *Users) download(records []model.SysUser) *bytes.Reader {
	f := excelize.NewFile() // 设置单元格的值
	// 这里设置表头
	f.SetCellValue("Sheet1", "A1", "用户账号")
	f.SetCellValue("Sheet1", "B1", "用户姓名")
	f.SetCellValue("Sheet1", "C1", "头像")
	f.SetCellValue("Sheet1", "D1", "性别")
	f.SetCellValue("Sheet1", "E1", "手机号")
	f.SetCellValue("Sheet1", "F1", "部门")
	f.SetCellValue("Sheet1", "G1", "状态")

	line := 1

	// 循环写入数据
	for _, v := range records {
		line++
		f.SetCellValue("Sheet1", fmt.Sprintf("A%d", line), v.Username)
		f.SetCellValue("Sheet1", fmt.Sprintf("B%d", line), v.Realname)
		f.AddPicture("Sheet1", fmt.Sprintf("C%d", line), "static/uploads/images/2022/09/8a1a001e-62e1-4968-84ef-ec6068201c68.jpg", "")
		//f.SetCellValue("Sheet1", fmt.Sprintf("C%d", line), v.Avatar)
		f.SetCellValue("Sheet1", fmt.Sprintf("D%d", line), v.Sex)
		f.SetCellValue("Sheet1", fmt.Sprintf("E%d", line), v.Phone)
		f.SetCellValue("Sheet1", fmt.Sprintf("F%d", line), v.DepartIds)
		f.SetCellValue("Sheet1", fmt.Sprintf("G%d", line), v.Status)
	}

	var buffer bytes.Buffer
	_ = f.Write(&buffer)
	content := bytes.NewReader(buffer.Bytes())
	return content
	//// 保存文件
	//if err := f.SaveAs("userList.xlsx"); err != nil {
	//	return err
	//}
	return nil
}

如果觉得我的文章对您有用,请随意赞赏。您的支持将鼓励我继续创作!