-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsscsv.go
59 lines (46 loc) · 1.07 KB
/
sscsv.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
package sscsv
import (
"context"
"errors"
"os"
"strings"
"google.golang.org/api/option"
"google.golang.org/api/sheets/v4"
)
var (
filename = os.Getenv("HOME") + "/.config/cred.json"
)
func GetCSVFromSpreadsheet(spreadsheetID, sheet string) (csv string, err error) {
srv, err := sheets.NewService(context.TODO(), option.WithCredentialsFile(filename))
if err != nil {
return
}
resp, err := srv.Spreadsheets.Values.Get(spreadsheetID, sheet).Do()
if err != nil {
return
}
if len(resp.Values) == 0 {
return "", errors.New("No data found")
}
rows := make([]string, len(resp.Values))
for i, row := range resp.Values {
colomns := make([]string, len(row))
for j, c := range row {
s := Escape(c.(string))
colomns[j] = s
}
rows[i] = strings.Join(colomns, ",")
}
csv = strings.Join(rows, "\n")
return
}
func Escape(s string) string {
x := strings.Replace(s, ",", "_+_", -1)
x = strings.Replace(x, "\n", "\\n", -1)
return x
}
func Unescape(s string) string {
x := strings.Replace(s, "_+_", ",", -1)
x = strings.Replace(x, "\\n", "\n", -1)
return x
}