代碼如下:
gin 方法 func ImportDiamonds(c *gin.Context) { var data models.Diamonds form, _ := c.MultipartForm() files := form.File["upload"] guid := uuid.New().String() filePath := "static/uploadfile/" + guid + ".xlsx" for _, file := range files { fmt.Println(file.Filename) _ = c.SaveUploadedFile(file, filePath) } if filePath == "" { c.JSON(400,gin.H{ "msg":"沒有這樣的文件", "code":400, }) } data.CreateBy = tools.GetUserIdStr(c) err := data.ImportPro(filePath) tools.HasError(err, "import fail", 500) app.OK(c, nil, "import success") } // 讀取方法 func (e *Diamonds) ImportPro(filePath string) error { xlFile, err := xlsx.OpenFile(filePath) if err != nil { fmt.Println(err) } //獲取行數 // length := len(xlFile.Sheets[0].Rows) //開辟除表頭外的行數的數組內存 // resourceArr := make([]string, length-1) for _, sheet := range xlFile.Sheets { //遍歷每一行 for rowIndex, row := range sheet.Rows { //跳過第一行表頭信息 if rowIndex == 0 { // for _, cell := range row.Cells { // text := cell.String() // fmt.Printf("%s\n", text) // } continue } //遍歷每一個單元 msg := Msg{} msg.Price = row.Cells[0].Value msg.Weight = row.Cells[1].Value msg.Color = row.Cells[2].Value msg.Neatness = row.Cells[3].Value msg.Cut = row.Cells[4].Value msg.Symmetric = row.Cells[5].Value msg.Polishing = row.Cells[6].Value msg.Fluorescence = row.Cells[7].Value msg.Shape = row.Cells[8].Value msg.Certificate = row.Cells[9].Value msg.Location = row.Cells[10].Value msg.Classify = 1 e.AddDiamonds(msg.Color,msg.Neatness,msg.Cut,msg.Symmetric,msg.Polishing,msg.Fluorescence,msg.Shape,msg.Certificate,msg.Location,msg.Classify) fmt.Println("msg:------ ",msg) \ } } return nil // fmt.Println(resourceArr) // return resourceArr } // 入庫gorm func (e *Diamonds) AddDiamonds( color string,neatness string, cut string, symmetric string ,polishing string, fluorescence string, shape string, certificate string,location string,classify int) error { doc := Diamonds{ Certificate:certificate, // 證書 Color : color, // 顏色 Cut : cut, // 切工 Fluorescence: fluorescence, // 熒光 Neatness : neatness, // 凈度 Polishing : polishing, // 拋光 Shape : shape, // 形狀 Symmetric : symmetric, // 對稱 Location : location, //位置 // Weight : weight, // 重量 // Price : price, // 價格 Classify : classify, // 分類 } fmt.Println(doc) result := orm.Eloquent.Table(e.TableName()).Create(&doc) if result.Error != nil { err := result.Error return err } return nil } type Msg struct { Price string // 價格 Weight string // 重量 Color string // 顏色 Neatness string // 凈度 Cut string // 切工 Symmetric string // 對稱 Polishing string // 拋光 Fluorescence string // 熒光 Shape string // 形狀 Certificate string // 證書 CertificateNum string // 證書號 Location string // 位置 Classify int // 0為用戶手動添加 1為報表導入 }