excel.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package excelizeutil
  2. import (
  3. "Cold_Logistic/internal/pkg/common/codex"
  4. "Cold_Logistic/internal/pkg/common/global"
  5. "context"
  6. "io"
  7. "strings"
  8. "gogs.baozhida.cn/Cold_Logistic_libs/pkg/contrib/errors"
  9. "gogs.baozhida.cn/Cold_Logistic_libs/pkg/contrib/util/goroutineutil"
  10. )
  11. type CheckFunc func(*excelize.File) error
  12. func CheckFileFormat(file *excelize.File, titles []string, titleRow, titleCel int, opts ...CheckFunc) error {
  13. sheet := file.GetSheetName(file.GetActiveSheetIndex())
  14. rows, err := file.GetRows(sheet)
  15. if err != nil {
  16. return errors.WithStack(err)
  17. }
  18. if len(rows) < 1 || len(rows[titleRow])-titleCel < len(titles) {
  19. return errors.WithCode(codex.ErrParamValidate, "文件标题头不匹配")
  20. }
  21. if len(rows) < 2 {
  22. return errors.WithCode(codex.ErrParamValidate, "导入文件内容为空")
  23. }
  24. // 校验表头
  25. for k, v := range titles {
  26. title := strings.TrimSpace(rows[titleRow][k+titleCel])
  27. if title != v {
  28. return errors.WithCode(codex.ErrParamValidate, "文件标题头不匹配")
  29. }
  30. }
  31. for _, o := range opts {
  32. if err = o(file); err != nil {
  33. return errors.WithStackOnce(err)
  34. }
  35. }
  36. return nil
  37. }
  38. func PutFile(ctx context.Context, keyPath string, file *excelize.File) (string, error) {
  39. // 更新结果上传至cos
  40. piper, pipeW := io.Pipe()
  41. defer piper.Close()
  42. goroutineutil.SafeGoWithCtx(ctx, func(c context.Context) {
  43. defer pipeW.Close()
  44. file.Write(pipeW)
  45. })
  46. oss := global.CommonConnectRepoInst.ObjectStore
  47. err := oss.PutObject(ctx, keyPath, piper)
  48. if err != nil {
  49. return "", errors.WithStackOnce(err)
  50. }
  51. return oss.GetDownLoadUrl(ctx, keyPath)
  52. }