Cron_Admin/app/utils/helper/import.go

70 lines
1.5 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package helper
import (
"fmt"
"github.com/go-kratos/kratos/v2/transport/http"
"github.com/pkg/errors"
"github.com/xuri/excelize/v2"
"strconv"
)
func ImportFile(ctx http.Context) (map[string][]int32, error) {
// 获取上传的文件
file, _, err := ctx.Request().FormFile("file")
if err != nil {
return nil, fmt.Errorf("failed to get form file: %w", err)
}
defer file.Close()
// 解析Excel文件
f, err := excelize.OpenReader(file)
if err != nil {
return nil, fmt.Errorf("failed to open excel file: %w", err)
}
defer f.Close()
// 获取第一个工作表的名称
sheetNames := f.GetSheetList()
if len(sheetNames) == 0 {
return nil, fmt.Errorf("无效的excel未获取到对应的sheet")
}
// 获取所有行
rows, err := f.GetRows(sheetNames[0])
if err != nil {
return nil, fmt.Errorf("failed to get rows from Excel sheet: %w", err)
}
if len(rows) == 0 {
return nil, fmt.Errorf("无效的excel未获取到对应的记录数据")
}
actualHeaders := rows[0] // 获取第一行作为表头
var key int
for i, v := range actualHeaders {
if v == "ID" {
key = i
}
}
// 定义一个map来存储订单ID到SendInfo的映射
var ids []int32
// 遍历行并处理数据
for i, row := range rows {
if i == 0 {
continue // 跳过头栏
}
if row[key] != "" {
id, _ := strconv.Atoi(row[key])
ids = append(ids, int32(id))
}
}
if len(ids) == 0 {
return nil, errors.New("未获取到数据")
}
idsPb := map[string][]int32{"ids": ids}
return idsPb, nil
}