-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathread_xlsx.go
65 lines (55 loc) · 1.16 KB
/
read_xlsx.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
package pandat
import (
"github.com/xuri/excelize/v2"
"io"
"os"
)
type ReadXlsxOption struct {
NoHeader bool
Sheet string
SheetIndex int
Password string
RawCellValue bool
}
func ReadXlsxPath(filepath string, option ReadXlsxOption) (*DataFrame[any], error) {
r, err := os.Open(filepath)
if err != nil {
return nil, err
}
return ReadXlsx(r, option)
}
func ReadXlsx(r io.Reader, option ReadXlsxOption) (*DataFrame[any], error) {
f, err := excelize.OpenReader(r, excelize.Options{
Password: option.Password,
RawCellValue: option.RawCellValue,
})
if err != nil {
return nil, err
}
sheets := f.GetSheetList()
if len(sheets) == 0 {
// empty excel
return NewDataFrame[any](), nil
}
var sheet string
if option.Sheet != "" {
sheet = option.Sheet
} else {
sheet = sheets[option.SheetIndex]
}
records, err := f.GetRows(sheet)
if err != nil {
return nil, err
}
if len(records) == 0 {
// empty sheet
return NewDataFrame[any](), nil
}
data := make([][]string, len(records[0]))
for _, row := range records {
for ncol, val := range row {
data[ncol] = append(data[ncol], val)
}
}
return ReadSlice(data, true), nil
}