You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

102 lines
2.8 KiB
Go

package common
import (
"fmt"
"github.com/mizuki1412/go-core-kit/class/exception"
"github.com/mizuki1412/go-core-kit/library/mathkit"
"github.com/mizuki1412/go-core-kit/service/configkit"
"github.com/mizuki1412/go-core-kit/service/logkit"
"github.com/spf13/cast"
"github.com/xuri/excelize/v2"
"os"
"path/filepath"
"strings"
"time"
)
type summary struct {
Quantity float64
Amount float64
}
func GenExcelFile() {
folderPath := cast.ToString(configkit.Get("folderPath", ""))
if folderPath == "" {
panic(exception.New("folder path is empty"))
}
templatePath := cast.ToString(configkit.Get("templatePath", ""))
if templatePath == "" {
panic(exception.New("templatePath is empty"))
}
files, err := os.ReadDir(folderPath)
if err != nil {
panic(exception.New(err.Error()))
}
f, err := excelize.OpenFile(templatePath)
if err != nil {
panic(exception.New(err.Error()))
}
// 存储按列号汇总的数据
index := 3
for _, file := range files {
if !file.IsDir() && strings.HasSuffix(file.Name(), ".xlsx") {
filePath := filepath.Join(folderPath, file.Name())
logkit.Info("处理文件:" + filePath)
summaryMap, projectName := processFile(filePath)
for col, s := range summaryMap {
f.SetCellValue("汇总表", fmt.Sprintf("A%d", index), projectName)
f.SetCellValue("汇总表", col+fmt.Sprintf("%d", index), cast.ToFloat64(mathkit.FloatRound(s.Quantity, 2)))
f.SetCellValue("汇总表", col+fmt.Sprintf("%d", index+1), cast.ToFloat64(mathkit.FloatRound(s.Amount, 2)))
}
index += 2
}
}
// Save the file
if err := f.SaveAs("/Users/leo/Documents/ERP材料核对/材料汇总(" + time.Now().Format("1月2日") + ").xlsx"); err != nil {
panic(exception.New(err.Error()))
}
logkit.Info("生成结束...")
}
// 处理单个excel
func processFile(filePath string) (map[string]*summary, string) {
f, err := excelize.OpenFile(filePath)
if err != nil {
panic(exception.New(err.Error()))
}
defer f.Close()
sheetList := f.GetSheetList()
if len(sheetList) == 0 {
panic(exception.New("无Sheet"))
}
sheet := sheetList[0] //获取第一个Sheet
projectName, _ := f.GetCellValue(sheet, "B3")
summaryMap := make(map[string]*summary)
row := 5
for {
eCell, err := f.GetCellValue(sheet, fmt.Sprintf("E%d", row))
if err != nil {
panic(exception.New(err.Error()))
}
if eCell == "" {
break
}
kCell, _ := f.GetCellValue(sheet, fmt.Sprintf("K%d", row))
mCell, _ := f.GetCellValue(sheet, fmt.Sprintf("M%d", row))
quantity := cast.ToFloat64(kCell)
amount := cast.ToFloat64(mCell)
col := getMatType(eCell)
if strings.Contains(col, "~") {
quantity /= 1000
col = strings.ReplaceAll(col, "~", "")
}
if summaryMap[col] == nil {
summaryMap[col] = &summary{}
}
summaryMap[col].Quantity += quantity
summaryMap[col].Amount += amount
row++
}
return summaryMap, projectName
}