123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120 |
- package excel
- import (
- "fmt"
- "kpt-tmr-group/config"
- "kpt-tmr-group/model"
- "kpt-tmr-group/pkg/di"
- "math/rand"
- "time"
- "github.com/gin-gonic/gin"
- "github.com/xuri/excelize/v2"
- )
- type SheetService interface {
- ExportToPath(params []map[string]string, data []map[string]interface{}, path string) (string, error)
- ExportToWeb(params []map[string]string, data []map[string]interface{}, c *gin.Context)
- writeTop(params []map[string]string)
- writeData(params []map[string]string, data []map[string]interface{})
- Export(params []map[string]string, data []map[string]interface{})
- }
- var Module = di.Provide(NewMyExcel)
- func NewMyExcel(cfg *config.AppConfig) *ExcelServer {
- return &ExcelServer{File: createFile(cfg), SheetName: cfg.ExcelSetting.SheetName}
- }
- func createFile(cfg *config.AppConfig) *excelize.File {
- f := excelize.NewFile()
- // 创建一个默认工作表
- index, _ := f.NewSheet(cfg.ExcelSetting.SheetName)
- // 设置工作簿的默认工作表
- f.SetActiveSheet(index)
- return f
- }
- func createFileName() string {
- name := time.Now().Format(model.LayoutTime)
- rand.Seed(time.Now().UnixNano())
- return fmt.Sprintf("excle-%v-%v.xlsx", name, rand.Int63n(time.Now().Unix()))
- }
- /*import (
- "go-excel/app/excelize"
- "go-excel/app/model"
- config "go-excel/common"
- "github.com/gin-gonic/gin"
- )
- //获取所有用户数据-excel
- func GetAllUserExportToWeb(ctx *gin.Context) {
- var users []model.TUser
- db := config.GetDB()
- db.Find(&users)
- //定义首行标题
- dataKey := make([]map[string]string, 0)
- dataKey = append(dataKey, map[string]string{
- "key": "id",
- "title": "索引",
- "width": "20",
- "is_num": "0",
- })
- dataKey = append(dataKey, map[string]string{
- "key": "username",
- "title": "用户名",
- "width": "20",
- "is_num": "0",
- })
- dataKey = append(dataKey, map[string]string{
- "key": "remark",
- "title": "备注",
- "width": "20",
- "is_num": "0",
- })
- //填充数据
- data := make([]map[string]interface{}, 0)
- if len(users) > 0 {
- for _, v := range users {
- data = append(data, map[string]interface{}{
- "id": v.ID,
- "username": v.Username,
- "remark": v.Remark,
- })
- }
- }
- ex := excelize.NewMyExcel()
- // ex.ExportToWeb(dataKey, data, ctx)
- //保存到D盘
- ex.ExportToPath(dataKey, data, "D:/")
- }
- //excel 导出
- func GetUserExcelByMap(ctx *gin.Context) {
- var users []model.TUser
- db := config.GetDB()
- db.Find(&users)
- titles := []string{"ID", "用户名", "备注"}
- ex := excelize.NewMyExcel()
- var datas []interface{}
- for _, v := range users {
- //这里最好新建一个struct 和titles一致,不然users里面的多余的字段也会写进去
- datas = append(datas, model.TUser{
- ID: v.ID,
- Username: v.Username,
- Remark: v.Remark,
- })
- }
- ex.ExportExcelByStruct(titles, datas, "用户数据", "用户", ctx)
- }*/
|