GoLang+gin框架导入Excel
安装
go get github.com/xuri/excelize/v2
控制器
func (e Users) UserImport(c *gin.Context) { srv := service.Users{} err := e.MakeContext(c).MakeOrm().MakeService(&srv.Service).Errors if err != nil { e.Error(0, "", err.Error()) return } var fileResponse uploads.FileResponse srv1 := uploads.Files{} urlPrefix := fmt.Sprintf("http://%s/", c.Request.Host) resp, done := srv1.SingleFile(c, fileResponse, urlPrefix) if done { return } srv.UserImport(resp.Path) }
服务层
func (e *Users) UserImport(file string) { f, err := excelize.OpenFile(file) if err != nil { fmt.Println(err) return } defer func() { if err := f.Close(); err != nil { fmt.Println(err) } }() /*// 获取工作表中指定单元格的值 cell, err := f.GetCellValue("Sheet1", "B2") if err != nil { fmt.Println(err) return } fmt.Println(cell)*/ // 获取 Sheet1 上所有单元格 rows, err := f.GetRows("Sheet1") if err != nil { fmt.Println(err) return } for i, row := range rows { if i > 0 { for _, colCell := range row { fmt.Print(colCell, "\t") } fmt.Println() } } }