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.
121 lines
3.2 KiB
Plaintext
121 lines
3.2 KiB
Plaintext
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.1.0"
|
|
|
|
// Чтение конфига
|
|
func readConfig(filename string) (Config, error) {
|
|
f := os.Open(filename)?
|
|
defer f.Close()
|
|
|
|
cfg := Config{}
|
|
decoder := yaml.NewDecoder(f)
|
|
decoder.Decode(&cfg)?
|
|
return cfg, nil
|
|
}
|
|
|
|
// Получаем все строки листа
|
|
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 > 26 {
|
|
echo `Столбец: ${col} вне диапазона столбцов: A-Z`
|
|
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", "V", "W", "X", "Y", "Z"}
|
|
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} сформирован`
|
|
}
|
|
|
|
// ====================== основная программа ====================
|
|
if len(os.Args) < 2 {
|
|
panic "Используй: tsa.exe <CONFIG>"
|
|
}
|
|
cfg := readConfig(os.Args[1])!
|
|
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)
|
|
|