github.com/easysoft/zendata@v0.0.0-20240513203326-705bd5a7fd67/internal/pkg/helper/md5.go (about) 1 package helper 2 3 import ( 4 "crypto/md5" 5 "encoding/hex" 6 "fmt" 7 "strconv" 8 "strings" 9 "time" 10 11 "github.com/360EntSecGroup-Skylar/excelize/v2" 12 i118Utils "github.com/easysoft/zendata/pkg/utils/i118" 13 logUtils "github.com/easysoft/zendata/pkg/utils/log" 14 ) 15 16 const ( 17 md5Col = "CW" 18 ) 19 20 func AddMd5(path, salt string) { 21 excel, err := excelize.OpenFile(path) 22 if err != nil { 23 logUtils.PrintTo(i118Utils.I118Prt.Sprintf("fail_to_read_file", path)) 24 return 25 } 26 27 for _, sheet := range excel.GetSheetList() { 28 rows, _ := excel.GetRows(sheet) 29 30 colCount := 0 31 for index, row := range rows { 32 if index == 0 { // deal with the title 33 for _, col := range rows[index] { 34 val := strings.TrimSpace(col) 35 if val == "" { 36 break 37 } 38 colCount++ 39 } 40 continue 41 } 42 43 if row[0] == "" { // stop when finding a blank in first column 44 break 45 } 46 47 str := "" 48 for idx, col := range row { 49 if idx >= colCount { 50 break 51 } 52 53 val := strings.TrimSpace(col) 54 str = str + val 55 } 56 md5Str := md5V(str, salt) 57 excel.SetCellValue(sheet, md5Col+strconv.Itoa(index+1), md5Str) 58 } 59 } 60 61 if err := excel.SaveAs(path); err != nil { 62 logUtils.PrintTo(i118Utils.I118Prt.Sprintf("fail_to_write_file", path)) 63 } 64 } 65 66 func md5V(str, salt string) (ret string) { 67 if salt == "" { 68 salt = fmt.Sprintf("%d", time.Now().Unix()) 69 } 70 71 h := md5.New() 72 73 h.Write([]byte(str)) 74 h.Write([]byte(salt)) 75 76 st := h.Sum(nil) 77 78 ret = hex.EncodeToString(st) 79 80 return 81 }