forked from qax-os/excelize
-
Notifications
You must be signed in to change notification settings - Fork 0
/
file.go
212 lines (198 loc) · 5.54 KB
/
file.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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
// Copyright 2016 - 2021 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
// and read from XLSX / XLSM / XLTM files. Supports reading and writing
// spreadsheet documents generated by Microsoft Excel™ 2007 and later. Supports
// complex components by high compatibility, and provided streaming API for
// generating or reading data from a worksheet with huge amounts of data. This
// library needs Go version 1.15 or later.
package excelize
import (
"archive/zip"
"bytes"
"fmt"
"io"
"os"
"path/filepath"
"sync"
)
// NewFile provides a function to create new file by default template. For
// example:
//
// f := NewFile()
//
func NewFile() *File {
f := newFile()
f.Pkg.Store("_rels/.rels", []byte(XMLHeader+templateRels))
f.Pkg.Store("docProps/app.xml", []byte(XMLHeader+templateDocpropsApp))
f.Pkg.Store("docProps/core.xml", []byte(XMLHeader+templateDocpropsCore))
f.Pkg.Store("xl/_rels/workbook.xml.rels", []byte(XMLHeader+templateWorkbookRels))
f.Pkg.Store("xl/theme/theme1.xml", []byte(XMLHeader+templateTheme))
f.Pkg.Store("xl/worksheets/sheet1.xml", []byte(XMLHeader+templateSheet))
f.Pkg.Store("xl/styles.xml", []byte(XMLHeader+templateStyles))
f.Pkg.Store("xl/workbook.xml", []byte(XMLHeader+templateWorkbook))
f.Pkg.Store("[Content_Types].xml", []byte(XMLHeader+templateContentTypes))
f.SheetCount = 1
f.CalcChain = f.calcChainReader()
f.Comments = make(map[string]*xlsxComments)
f.ContentTypes = f.contentTypesReader()
f.Drawings = sync.Map{}
f.Styles = f.stylesReader()
f.DecodeVMLDrawing = make(map[string]*decodeVmlDrawing)
f.VMLDrawing = make(map[string]*vmlDrawing)
f.WorkBook = f.workbookReader()
f.Relationships = sync.Map{}
f.Relationships.Store("xl/_rels/workbook.xml.rels", f.relsReader("xl/_rels/workbook.xml.rels"))
f.sheetMap["Sheet1"] = "xl/worksheets/sheet1.xml"
ws, _ := f.workSheetReader("Sheet1")
f.Sheet.Store("xl/worksheets/sheet1.xml", ws)
f.Theme = f.themeReader()
return f
}
// Save provides a function to override the spreadsheet with origin path.
func (f *File) Save() error {
if f.Path == "" {
return fmt.Errorf("no path defined for file, consider File.WriteTo or File.Write")
}
return f.SaveAs(f.Path)
}
// SaveAs provides a function to create or update to an spreadsheet at the
// provided path.
func (f *File) SaveAs(name string, opt ...Options) error {
if len(name) > MaxFileNameLength {
return ErrMaxFileNameLength
}
f.Path = name
file, err := os.OpenFile(filepath.Clean(name), os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0600)
if err != nil {
return err
}
defer file.Close()
f.options = nil
for i := range opt {
f.options = &opt[i]
}
return f.Write(file)
}
// Close closes and cleanup the open temporary file for the spreadsheet.
func (f *File) Close() error {
var err error
f.tempFiles.Range(func(k, v interface{}) bool {
if err = os.Remove(v.(string)); err != nil {
return false
}
return true
})
return err
}
// Write provides a function to write to an io.Writer.
func (f *File) Write(w io.Writer) error {
_, err := f.WriteTo(w)
return err
}
// WriteTo implements io.WriterTo to write the file.
func (f *File) WriteTo(w io.Writer) (int64, error) {
if f.options != nil && f.options.Password != "" {
buf, err := f.WriteToBuffer()
if err != nil {
return 0, err
}
return buf.WriteTo(w)
}
if err := f.writeDirectToWriter(w); err != nil {
return 0, err
}
return 0, nil
}
// WriteToBuffer provides a function to get bytes.Buffer from the saved file,
// and it allocates space in memory. Be careful when the file size is large.
func (f *File) WriteToBuffer() (*bytes.Buffer, error) {
buf := new(bytes.Buffer)
zw := zip.NewWriter(buf)
if err := f.writeToZip(zw); err != nil {
return buf, zw.Close()
}
if f.options != nil && f.options.Password != "" {
if err := zw.Close(); err != nil {
return buf, err
}
b, err := Encrypt(buf.Bytes(), f.options)
if err != nil {
return buf, err
}
buf.Reset()
buf.Write(b)
return buf, nil
}
return buf, zw.Close()
}
// writeDirectToWriter provides a function to write to io.Writer.
func (f *File) writeDirectToWriter(w io.Writer) error {
zw := zip.NewWriter(w)
if err := f.writeToZip(zw); err != nil {
_ = zw.Close()
return err
}
return zw.Close()
}
// writeToZip provides a function to write to zip.Writer
func (f *File) writeToZip(zw *zip.Writer) error {
f.calcChainWriter()
f.commentsWriter()
f.contentTypesWriter()
f.drawingsWriter()
f.vmlDrawingWriter()
f.workBookWriter()
f.workSheetWriter()
f.relsWriter()
f.sharedStringsWriter()
f.styleSheetWriter()
var pathDone = make(map[string]bool)
for _, d := range f.directWriters {
fi, err := zw.Create(d.sheetPath)
if err != nil {
return err
}
if _, err := d.WriteTo(fi); err != nil {
return err
}
pathDone[d.sheetPath] = true
}
for path, stream := range f.streams {
fi, err := zw.Create(path)
if err != nil {
return err
}
var from io.Reader
from, err = stream.rawData.Reader()
if err != nil {
_ = stream.rawData.Close()
return err
}
_, err = io.Copy(fi, from)
if err != nil {
return err
}
_ = stream.rawData.Close()
pathDone[path] = true
}
var err error
f.Pkg.Range(func(path, content interface{}) bool {
if err != nil {
return false
}
if _, ok := pathDone[path.(string)]; ok {
return true
}
var fi io.Writer
fi, err = zw.Create(path.(string))
if err != nil {
return false
}
_, err = fi.Write(content.([]byte))
return true
})
return err
}