omq/export_csv.go

74 lines
1006 B
Go

package main
import (
"encoding/csv"
"fmt"
"os"
"time"
)
// Экспорт в CSV
type CsvExporter struct {
Encoding Encoding
}
func (c *CsvExporter) FileExt() string {
return ".csv"
}
func (c *CsvExporter) Convert(filePath string, rows chan []any) error {
f, err := os.Create(filePath + c.FileExt())
if err != nil {
return err
}
enc, err := c.Encoding.Encoder()
if err != nil {
return err
}
w := csv.NewWriter(enc.Writer(f))
w.Comma = ';'
rowNum := 0
for row := range rows {
rowNum++
rowsStr := make([]string, len(row))
for i := range row {
rowsStr[i] = toCsvField(row[i])
}
err = w.Write(rowsStr)
if err != nil {
f.Close()
return err
}
}
w.Flush()
if err = w.Error(); err != nil {
f.Close()
return err
}
err = f.Close()
if err != nil {
return err
}
return nil
}
func toCsvField(a any) string {
if a == nil {
return ""
}
switch v := a.(type) {
case time.Time:
return v.Format("02.01.2006 15:04:05")
}
return fmt.Sprint(a)
}