-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathexcel.go
More file actions
76 lines (67 loc) · 1.55 KB
/
excel.go
File metadata and controls
76 lines (67 loc) · 1.55 KB
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
package main
import (
"bytes"
"fmt"
"strings"
"github.com/xuri/excelize/v2"
)
// ExcelData holds the parsed contents of an Excel file.
type ExcelData struct {
Headers []string `json:"headers"`
Rows []map[string]string `json:"rows"`
}
// ParseExcel reads the first sheet of an xlsx file and returns headers + rows.
// Row 1 is treated as headers (variable names). Rows 2+ are data.
func ParseExcel(fileBytes []byte) (*ExcelData, error) {
f, err := excelize.OpenReader(bytes.NewReader(fileBytes))
if err != nil {
return nil, fmt.Errorf("open excel: %w", err)
}
defer f.Close()
sheetName := f.GetSheetName(0)
if sheetName == "" {
return nil, fmt.Errorf("no sheets found")
}
rows, err := f.GetRows(sheetName)
if err != nil {
return nil, fmt.Errorf("read rows: %w", err)
}
if len(rows) < 1 {
return nil, fmt.Errorf("empty sheet")
}
// Row 0 = headers
headers := make([]string, len(rows[0]))
for i, h := range rows[0] {
headers[i] = strings.TrimSpace(h)
}
// Rows 1+ = data
data := make([]map[string]string, 0, len(rows)-1)
for _, row := range rows[1:] {
record := make(map[string]string, len(headers))
for i, header := range headers {
if header == "" {
continue
}
val := ""
if i < len(row) {
val = strings.TrimSpace(row[i])
}
record[header] = val
}
// Skip completely empty rows
empty := true
for _, v := range record {
if v != "" {
empty = false
break
}
}
if !empty {
data = append(data, record)
}
}
return &ExcelData{
Headers: headers,
Rows: data,
}, nil
}