-
Notifications
You must be signed in to change notification settings - Fork 2
/
content_type.go
78 lines (62 loc) · 1.53 KB
/
content_type.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
package main
import (
"encoding/xml"
"path/filepath"
"strings"
)
type ContentTypesOverride struct {
PartName string `xml:"PartName,attr"`
ContentType string `xml:"ContentType,attr"`
}
type ContentTypesDefault struct {
Extension string `xml:"Extension,attr"`
ContentType string `xml:"ContentType,attr"`
}
type ContentTypes struct {
Xlsx *Xlsx
XMLName xml.Name `xml:"Types"`
Override []*ContentTypesOverride
Default []*ContentTypesDefault
}
func (ct *ContentTypes) GetPartNameByType(contentType string) (partName []string, ok bool) {
for _, ov := range ct.Override {
if ov.ContentType == contentType {
partName = append(partName, strings.TrimLeft(ov.PartName, "/"))
}
}
if len(partName) == 0 {
for _, df := range ct.Default {
if df.ContentType == contentType {
for _, f := range ct.Xlsx.Files {
ext := strings.TrimLeft(filepath.Ext(f.Name), ".")
if ext == df.Extension {
partName = append(partName, strings.TrimLeft(f.Name, "/"))
}
}
}
}
}
return partName, len(partName) > 0
}
func NewContentType(xlsx *Xlsx) (ct *ContentTypes, err error) {
ct = &ContentTypes{}
ct.Xlsx = xlsx
var fName string
for k, f := range xlsx.Files {
if strings.ToLower(f.Name) == strings.ToLower(ContentTypeFile) {
fName = k
break
}
}
contentTypeFile, err := xlsx.Files[fName].Open()
if err != nil {
return nil, err
}
defer contentTypeFile.Close()
xmlDecoder := xml.NewDecoder(contentTypeFile)
err = xmlDecoder.Decode(ct)
if err != nil {
return nil, err
}
return ct, err
}