omq/export_csv.go
2023-11-17 20:34:20 +05:00

91 lines
1.3 KiB
Go

package main
import (
"archive/zip"
"encoding/csv"
"fmt"
"os"
"path/filepath"
"time"
)
// Экспорт в CSV, сжатый в ZIP-архив
type CsvExporter struct {
Encoding Encoding
}
func (c *CsvExporter) FileExt() string {
return ".zip"
}
func (c *CsvExporter) Convert(filePath string, rows chan []any) error {
f, err := os.Create(filePath + c.FileExt())
if err != nil {
return err
}
z := zip.NewWriter(f)
zw, err := z.Create(filepath.Base(filePath) + ".csv")
if err != nil {
f.Close()
return err
}
/*var enc io.Writer
if c.Encoding == EncodingWndows1251 {
enc = charmap.Windows1251.NewEncoder().Writer(zw)
} else {
enc = zw
}*/
enc, err := c.Encoding.Encoder()
if err != nil {
return err
}
w := csv.NewWriter(enc.Writer(zw))
w.Comma = ';'
for row := range rows {
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 w.Error() != nil {
f.Close()
return w.Error()
}
err = z.Close()
if err != nil {
f.Close()
return err
}
return f.Close()
}
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)
}