diff options
author | George Abbott <george@gabbott.dev> | 2023-11-03 19:14:28 +0000 |
---|---|---|
committer | George Abbott <george@gabbott.dev> | 2023-11-03 19:14:28 +0000 |
commit | 499fc1ce2a1a98c26dc5060e483168a2f47ca840 (patch) | |
tree | 13305978e2cf4894999ecbe778e645f641568680 /main.go |
Diffstat (limited to 'main.go')
-rw-r--r-- | main.go | 96 |
1 files changed, 96 insertions, 0 deletions
@@ -0,0 +1,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)) +} + |