summaryrefslogtreecommitdiff
path: root/main.go
blob: 8a3f8a701ea6b31270475f4dfcf980894750f0c2 (plain) (blame)
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
package main 

/* bt-splitsheet: split each sheet into its own workbook.
 */

import (
	"fmt"
	st "saggytrousers"
	bt "badtudexo"
	xl "anyxcelize"
	"time"
	"os"
	"path/filepath"
)

/* Globals */
var filename string
var gOutDir string = ""
var gPrintTime bool = false

func parseArgs(args []string) {
	if len(args) < 2 {
		fmt.Println("Pass either a filename, or --help or --version.")
		os.Exit(-1)
	}

	for i := 0; i < len(args); i++ {
		arg := args[i]
		switch arg {
		case "--help", "-h", "help":
			usage()
		case "--version", "-v", "version":
			version()
		case "-d", "--directory":
			i++
			gOutDir = args[i]
		case "-t", "--time":
			gPrintTime = true
		default:
			filename = arg
		}
	}
}

func main() {
	tBegin := time.Now()
	args := os.Args
	parseArgs(args)

	file, err := xl.OpenFile(filename)
	if err != nil {
		fmt.Printf("Cannot open file [%s], err [%v]\n", filename, err)
		return
	}

	fp := filepath.Dir(filename)
	var fn string
	var ldir string
	if gOutDir == "" {
		fn = filepath.Base(filename)
		ldir = fmt.Sprintf("Split-%v", fn)
	} else {
		fn = gOutDir
		ldir = fn
	}
	dir := fmt.Sprintf("%v/%v", fp, ldir)
	sheets := file.GetSheetMap()
	os.Mkdir(dir, 0777)
	for _, sheet := range sheets { /* sheets map: only want values */
		tStartSheet := time.Now()
		dest := fmt.Sprintf("%v/%v.xlsx", dir, sheet)
		fmt.Printf("Working on: %v\n", sheet)
		err, wasEmpty := bt.Copy(/* from: */ file, sheet,
			       /* to:   */ dest,
			       /* fail if empty: */ true,
		)

		if wasEmpty {
			st.Log(true, fmt.Sprintf("Skipped sheet [%v] as it was empty.\n", sheet))
			continue
		}

		if err != nil {
			st.Log(true, fmt.Sprintf("Failed to save %v with error %v.\n", dest, err))
		} else {
			st.Log(true, fmt.Sprintf("Saved %v successfully.\n", dest))
		}

		st.Log(gPrintTime, fmt.Sprintf("Time for sheet %v: %v.\n", sheet, time.Since(tStartSheet)))

	}

	tElapsed := time.Since(tBegin)
	st.Log(gPrintTime, fmt.Sprintf("From beginning to end: %v.\n", tElapsed))
}