-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
86 lines (67 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
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"path"
"path/filepath"
"strings"
"github.com/go-ole/go-ole"
"github.com/go-ole/go-ole/oleutil"
)
func main() {
ole.CoInitialize(0)
ea, err := oleutil.CreateObject("Excel.Application")
if err != nil {
log.Fatal(err)
}
defer ea.Release()
excel, _ := ea.QueryInterface(ole.IID_IDispatch)
defer excel.Release()
log.Printf("Excel Version: %s\n", oleutil.MustGetProperty(excel, "Version").ToString())
// oleutil.PutProperty(excel, "Visible", true) // hide window
oleutil.PutProperty(excel, "DisplayAlerts", false)
oleutil.PutProperty(excel, "ScreenUpdating", true)
target := os.Args[1]
fi, err := os.Stat(target)
if err != nil {
log.Fatal(err)
}
if fi.IsDir() {
files, _ := ioutil.ReadDir(target)
for i, file := range files {
file, _ := filepath.Abs(filepath.Join(target, file.Name()))
log.Printf("Processing #%d %s\n", i, file)
saveWorkbook(excel, file, "out")
}
} else {
saveWorkbook(excel, target, ".")
}
oleutil.MustCallMethod(excel, "Quit")
}
func saveWorkbook(excel *ole.IDispatch, file, dir string) {
workbooks := oleutil.MustGetProperty(excel, "WorkBooks").ToIDispatch()
defer workbooks.Release()
books := oleutil.MustCallMethod(workbooks, "open", file, nil, true).ToIDispatch()
defer books.Release()
sheets := oleutil.MustGetProperty(excel, "Sheets").ToIDispatch()
n := int(oleutil.MustGetProperty(sheets, "Count").Val)
sheets.Release()
log.Printf("Total %d sheet(s)\n", n)
name := filepath.Base(file)
name = strings.TrimSuffix(name, path.Ext(name))
const xlCSVUTF8 = 62
for i := 1; i <= n; i++ {
worksheets := oleutil.MustGetProperty(excel, "Worksheets", i).ToIDispatch()
oleutil.MustCallMethod(worksheets, "Select")
fp := filepath.Join(dir, fmt.Sprintf("%s-%d.csv", name, i))
fp, _ = filepath.Abs(fp)
log.Printf("Saving sheet#%d to %s\n", i, fp)
activeWorkBook := oleutil.MustGetProperty(excel, "ActiveWorkBook").ToIDispatch()
oleutil.MustCallMethod(activeWorkBook, "SaveAs", fp, xlCSVUTF8, nil, nil)
activeWorkBook.Release()
worksheets.Release()
}
oleutil.MustCallMethod(workbooks, "Close")
}