75 lines
1.1 KiB
Go
75 lines
1.1 KiB
Go
|
package main
|
||
|
|
||
|
import (
|
||
|
"archive/zip"
|
||
|
"encoding/csv"
|
||
|
"os"
|
||
|
"path/filepath"
|
||
|
)
|
||
|
|
||
|
// Экспорт в CSV, сжатый в ZIP-архив
|
||
|
type CsvZipExporter struct {
|
||
|
Encoding Encoding
|
||
|
}
|
||
|
|
||
|
func (c *CsvZipExporter) FileExt() string {
|
||
|
return ".zip"
|
||
|
}
|
||
|
|
||
|
func (c *CsvZipExporter) 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
|
||
|
}
|
||
|
|
||
|
enc, err := c.Encoding.Encoder()
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
w := csv.NewWriter(enc.Writer(zw))
|
||
|
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 = z.Close()
|
||
|
if err != nil {
|
||
|
f.Close()
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
err = f.Close()
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
return nil
|
||
|
}
|