-
Notifications
You must be signed in to change notification settings - Fork 13
/
excel.go
83 lines (61 loc) · 1.63 KB
/
excel.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package exporter
import (
"bytes"
"github.com/tealeg/xlsx"
)
type IXLSXExporter interface {
exportToFile(sheet string, columns []string, rows [][]interface{}, filePath string) error
exportToByte(sheet string, columns []string, rows [][]interface{}) ([]byte, error)
}
type XLSXExporter struct {
}
func NewXLSXExportService() *XLSXExporter {
return &XLSXExporter{}
}
func (e *XLSXExporter) exportToFile(sheet string, columns []string, rows [][]interface{}, filePath string) error {
xlsxFile, err := e.export(sheet, columns, rows)
if err != nil {
return err
}
return xlsxFile.Save(filePath)
}
func (e *XLSXExporter) exportToByte(sheet string, columns []string, rows [][]interface{}) ([]byte, error) {
xlsxFile, err := e.export(sheet, columns, rows)
if err != nil {
return nil, err
}
byteXLSX := new(bytes.Buffer)
err = xlsxFile.Write(byteXLSX)
if err != nil {
return nil, err
}
return byteXLSX.Bytes(), nil
}
func (e *XLSXExporter) export(sheet string, columns []string, rows [][]interface{}) (*xlsx.File, error) {
err := verifyRows(columns, rows)
if err != nil {
return nil, err
}
var xlsxFile *xlsx.File
var xlsxSheet *xlsx.Sheet
var xlsxRow *xlsx.Row
var xlsxCell *xlsx.Cell
xlsxFile = xlsx.NewFile()
xlsxSheet, err = xlsxFile.AddSheet(sheet)
if err != nil {
return nil, err
}
xlsxRow = xlsxSheet.AddRow()
for _, columnTitle := range columns {
xlsxCell = xlsxRow.AddCell()
xlsxCell.SetValue(columnTitle)
}
for _, row := range rows {
xlsxRow = xlsxSheet.AddRow()
for columnIndex := range columns {
xlsxCell = xlsxRow.AddCell()
xlsxCell.SetValue(row[columnIndex])
}
}
return xlsxFile, nil
}