import ( "os" //"fmt" "strconv" "math" "encoding/json" "github.com/go-yaml/yaml" "github.com/xuri/excelize/v2" ) type Config struct { FileName string `yaml:"inputFile"` JsonFile string `yaml:"outputFile"` SheetName string `yaml:"sheet"` StartRow int `yaml:"startRow"` Columns map[string]string `yaml:"columns"` } var VERSION = "0.0.1" // Чтение конфига func readConfig() Config { f := os.Open("tsa.yaml")! defer f.Close() cfg := Config{} decoder := yaml.NewDecoder(f) decoder.Decode(&cfg)! return cfg } // Получаем все строки листа func readExcel(filename, sheetname string) [][]string { f := excelize.OpenFile(filename)! defer f.Close() rows := f.GetRows(sheetname)! return rows } func getColumnName(cols map[string]string, col int) string { if col < 1 || col > 21 { echo `Столбец: ${col} вне диапазона столбцов` os.Exit(0) } type ColsMap struct { num int str string } colsmap := []string { " ","A","B","C","D","E","F","G","H","I", "J","K","L","M","N","O","P","Q","R","S", "T", "U"} return cols[colsmap[col]] } func convert2int (s string) int64 { f := strconv.ParseFloat(s, 64)! n := int64(f) // отбрасываем дробную часть return n } // выводит результат на экран func json2screen(dbValues []map[string]string) { //echo dbValues //b := json.Marshal(dbValues)! // для красоты: pretty := json.MarshalIndent(dbValues, "", " ")! //echo string(b) echo string(pretty) } func json2file(dbValues []map[string]string, outfile string) { f := os.OpenFile(outfile, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o644)! defer f.Close() // Создаём JSON-эндодер, который пишет напрямую в файл enc := json.NewEncoder(f) enc.SetIndent("", " ") // красивый отступ (можно убрать) // Сериализуем структуру в файл enc.Encode(dbValues)! echo `Файл ${outfile} сформирован` } // ====================== основная программа ==================== cfg := readConfig() rows := readExcel(cfg.FileName, cfg.SheetName) echo "Программа конвертации excel -> json. Версия ${VERSION}" echo "Файл ${cfg.FileName} содержит записей: ${len(rows)}" var dbValues = []map[string]string{} for row <- rows[cfg.StartRow-1:] { rowValues := make(map[string]string) for col, val <- row { colname := getColumnName(cfg.Columns, col+1) // преобразуем в целое if colname == "caseId" || colname == "policyNumber" { val = sprintf("%d", convert2int(val)) } // не определенные столбцы пропускаем if colname != "" { rowValues[colname] = val } //echo `${col} [${colname}]: ${val}` } dbValues = append(dbValues, rowValues) //printf "[%4d]: %v\n", line, row } //json2screen(dbValues) json2file(dbValues, cfg.JsonFile)