-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
128 lines (93 loc) · 1.9 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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package main
import (
"database/sql"
"fmt"
"os"
_ "github.com/denisenkom/go-mssqldb"
"github.com/tealeg/xlsx"
)
func main() {
fmt.Println("process started.")
fmt.Println("process in progress.")
db, err := initDB()
defer db.Close()
if err != nil {
panic("connect step issue: " + err.Error())
}
result, err := readDb(db)
defer result.Close()
if err != nil {
panic("read step issue: " + err.Error())
}
numbers := fillArray(result)
convertToCvs(numbers)
fmt.Println("process finished.")
}
func initDB() (*sql.DB, error) {
var (
server = "your_server"
port = 1433
user = "your_user"
password = "your_password"
database = "your_db_name"
)
connString := fmt.Sprintf("server=%s;user id=%s;password=%s;port=%d;database=%s;",
server, user, password, port, database)
db, err := sql.Open("mssql", connString)
if err != nil {
panic(err.Error())
}
fmt.Printf("Connected!\n")
return db, err
}
func readDb(db *sql.DB) (*sql.Rows, error) {
query := "your_query"
rows, err := db.Query(query)
if err != nil {
panic(err.Error())
}
return rows, err
}
func fillArray(rows *sql.Rows) []string {
numbers := []string{}
for rows.Next() {
var number string
err := rows.Scan(&number)
if err != nil {
panic(err.Error())
}
numbers = append(numbers, number)
}
return numbers
}
func convertToCvs(numbers []string) {
path := "numbers.xlsx"
if numbers == nil {
panic("array is empty")
}
_, err := os.Stat(path)
if os.IsExist(err) {
err := os.Remove(path)
if err != nil {
panic(err.Error())
}
}
var file *xlsx.File
var sheet *xlsx.Sheet
var row *xlsx.Row
var cell *xlsx.Cell
file = xlsx.NewFile()
sheet, err = file.AddSheet("Sheet1")
if err != nil {
panic(err.Error())
}
for _, num := range numbers {
row = sheet.AddRow()
cell = row.AddCell()
cell.Value = string(num)
}
err = file.Save(path)
if err != nil {
panic(err.Error())
}
}