-
Notifications
You must be signed in to change notification settings - Fork 69
/
Copy pathmain.go
104 lines (95 loc) · 2.18 KB
/
main.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
// Copyright 2011-2015, The xlsx2csv Authors.
// All rights reserved.
// For details, see the LICENSE file.
package main
import (
"encoding/csv"
"errors"
"flag"
"fmt"
"io"
"log"
"os"
"github.com/tealeg/xlsx/v3"
)
func generateCSVFromXLSXFile(w io.Writer, excelFileName string, sheetIndex int, csvOpts csvOptSetter) error {
xlFile, err := xlsx.OpenFile(excelFileName)
if err != nil {
return err
}
sheetLen := len(xlFile.Sheets)
switch {
case sheetLen == 0:
return errors.New("This XLSX file contains no sheets.")
case sheetIndex >= sheetLen:
return fmt.Errorf("No sheet %d available, please select a sheet between 0 and %d\n", sheetIndex, sheetLen-1)
}
cw := csv.NewWriter(w)
if csvOpts != nil {
csvOpts(cw)
}
sheet := xlFile.Sheets[sheetIndex]
var vals []string
err = sheet.ForEachRow(func(row *xlsx.Row) error {
if row != nil {
vals = vals[:0]
err := row.ForEachCell(func(cell *xlsx.Cell) error {
str, err := cell.FormattedValue()
if err != nil {
return err
}
vals = append(vals, str)
return nil
})
if err != nil {
return err
}
}
cw.Write(vals)
return nil
})
if err != nil {
return err
}
cw.Flush()
return cw.Error()
}
type csvOptSetter func(*csv.Writer)
func main() {
var (
outFile = flag.String("o", "-", "filename to output to. -=stdout")
sheetIndex = flag.Int("i", 0, "Index of sheet to convert, zero based")
delimiter = flag.String("d", ";", "Delimiter to use between fields")
)
flag.Usage = func() {
fmt.Fprintf(os.Stderr, `%s
dumps the given xlsx file's chosen sheet as a CSV,
with the specified delimiter, into the specified output.
Usage:
%s [flags] <xlsx-to-be-read>
`, os.Args[0], os.Args[0])
flag.PrintDefaults()
}
flag.Parse()
if flag.NArg() != 1 {
flag.Usage()
os.Exit(1)
}
out := os.Stdout
if !(*outFile == "" || *outFile == "-") {
var err error
if out, err = os.Create(*outFile); err != nil {
log.Fatal(err)
}
}
defer func() {
if closeErr := out.Close(); closeErr != nil {
log.Fatal(closeErr)
}
}()
if err := generateCSVFromXLSXFile(out, flag.Arg(0), *sheetIndex,
func(cw *csv.Writer) { cw.Comma = ([]rune(*delimiter))[0] },
); err != nil {
log.Fatal(err)
}
}