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.

153 lines
4.1 KiB
Plaintext

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import (
"os"
//"fmt"
"strconv"
"math"
"encoding/json"
"github.com/go-yaml/yaml"
"github.com/xuri/excelize/v2"
)
type Config struct {
FileName string `yaml:"file"`
SheetName string `yaml:"sheet"`
StartRow int `yaml:"start"`
Columns map[string]string `yaml:"columns"`
}
// Чтение конфига
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
}
// ====================== основная программа ====================
cfg := readConfig()
rows := readExcel(cfg.FileName, cfg.SheetName)
echo "Всего ${len(rows)} строк"
var dbValues = []map[string]string{}
for row <- rows[cfg.StartRow-1:2] {
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
}
//echo dbValues
b := json.Marshal(dbValues)!
// для красоты:
//pretty := json.MarshalIndent(dbValues, "", " ")!
echo string(b)
//echo string(pretty)
/*
rowsToRemove := []int{}
bkColor := ""
groupColor := "без цвета"
newGroup := false
newContent := ""
firstCell := "" // первая строка группы -> ячейка для замены
cellName := ""
for line, row <- rows if len(row) > 0 {
cellName = excelize.CoordinatesToCellName(8, line+1)! //H1..H13..
styleID := f.GetCellStyle(sheetName, cellName)!
style := f.GetStyle(styleID)!
fillColor := style.Fill.Color // это слайс строк с цветами заливки
if len(fillColor) > 0 {
bkColor = fillColor[0]
} else {
bkColor = "без цвета"
}
if bkColor != groupColor {
groupColor = bkColor
newGroup = true
// меняем значение для предыдущей группы
f.SetCellValue(sheetName, firstCell, newContent)
firstCell = cellName // запоминаем ячейку, которую потом будем менять
newContent = f.GetCellValue(sheetName, cellName)! // .. и ее содержимое
} else {
newGroup = false
newContent += ", " + f.GetCellValue(sheetName, cellName)!
}
if !newGroup {
// строка не первая в группе - удаляем
rowsToRemove = append(rowsToRemove, line)
}
printf "%v %s, %d [%d] = %#v\n", bkColor, cellName, line, len(row), row
}
// меняем значение для последней группы
f.SetCellValue(sheetName, firstCell, newContent)
newContent = f.GetCellValue(sheetName, cellName)! // .. и ее содержимое
//rowsToRemove = append(rowsToRemove, 3)
echo "удаляемые строки:", rowsToRemove
// Удаляем строки в обратном порядке (снизу вверх)
// первую строку не удаляем!
for i := len(rowsToRemove) - 1; i >= 1; i-- {
row := rowsToRemove[i] + 1
f.RemoveRow(sheetName, row)!
//echo "Удалена строка", row
}
f.SaveAs("result.xlsm")
*/