file.go 6.3 KB
Newer Older
1
// Copyright 2016 - 2024 The excelize Authors. All rights reserved. Use of
xurime's avatar
xurime 已提交
2 3 4
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
5 6 7 8 9
// Package excelize providing a set of functions that allow you to write to and
// read from XLAM / XLSM / XLSX / XLTM / XLTX 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
xurime's avatar
xurime 已提交
10
// data. This library needs Go version 1.16 or later.
xurime's avatar
xurime 已提交
11

xurime's avatar
xurime 已提交
12 13 14 15 16
package excelize

import (
	"archive/zip"
	"bytes"
17
	"encoding/xml"
J
Josh Fyne 已提交
18
	"io"
xurime's avatar
xurime 已提交
19
	"os"
xurime's avatar
xurime 已提交
20
	"path/filepath"
21
	"sort"
22
	"strings"
23
	"sync"
xurime's avatar
xurime 已提交
24 25
)

26 27
// NewFile provides a function to create new file by default template.
// For example:
28
//
29
//	f := NewFile()
30
func NewFile(opts ...Options) *File {
31
	f := newFile()
32
	f.Pkg.Store("_rels/.rels", []byte(xml.Header+templateRels))
33 34
	f.Pkg.Store(defaultXMLPathDocPropsApp, []byte(xml.Header+templateDocpropsApp))
	f.Pkg.Store(defaultXMLPathDocPropsCore, []byte(xml.Header+templateDocpropsCore))
35
	f.Pkg.Store(defaultXMLPathWorkbookRels, []byte(xml.Header+templateWorkbookRels))
36 37 38 39 40
	f.Pkg.Store("xl/theme/theme1.xml", []byte(xml.Header+templateTheme))
	f.Pkg.Store("xl/worksheets/sheet1.xml", []byte(xml.Header+templateSheet))
	f.Pkg.Store(defaultXMLPathStyles, []byte(xml.Header+templateStyles))
	f.Pkg.Store(defaultXMLPathWorkbook, []byte(xml.Header+templateWorkbook))
	f.Pkg.Store(defaultXMLPathContentTypes, []byte(xml.Header+templateContentTypes))
41
	f.SheetCount = 1
42
	f.CalcChain, _ = f.calcChainReader()
43
	f.ContentTypes, _ = f.contentTypesReader()
44
	f.Styles, _ = f.stylesReader()
45
	f.WorkBook, _ = f.workbookReader()
46
	f.Relationships = sync.Map{}
47 48
	rels, _ := f.relsReader(defaultXMLPathWorkbookRels)
	f.Relationships.Store(defaultXMLPathWorkbookRels, rels)
49
	f.sheetMap["Sheet1"] = "xl/worksheets/sheet1.xml"
50 51
	ws, _ := f.workSheetReader("Sheet1")
	f.Sheet.Store("xl/worksheets/sheet1.xml", ws)
52
	f.Theme, _ = f.themeReader()
53
	f.options = getOptions(opts...)
54
	return f
55 56
}

57
// Save provides a function to override the spreadsheet with origin path.
58
func (f *File) Save(opts ...Options) error {
J
Josh Fyne 已提交
59
	if f.Path == "" {
60
		return ErrSave
61
	}
62 63
	for i := range opts {
		f.options = &opts[i]
64
	}
65
	return f.SaveAs(f.Path, *f.options)
xurime's avatar
xurime 已提交
66 67
}

68
// SaveAs provides a function to create or update to a spreadsheet at the
xurime's avatar
xurime 已提交
69
// provided path.
70
func (f *File) SaveAs(name string, opts ...Options) error {
71 72
	if len(name) > MaxFilePathLength {
		return ErrMaxFilePathLength
73
	}
74
	f.Path = name
75
	if _, ok := supportedContentTypes[strings.ToLower(filepath.Ext(f.Path))]; !ok {
76
		return ErrWorkbookFileFormat
77
	}
78
	file, err := os.OpenFile(filepath.Clean(name), os.O_WRONLY|os.O_TRUNC|os.O_CREATE, os.ModePerm)
J
Josh Fyne 已提交
79 80 81 82
	if err != nil {
		return err
	}
	defer file.Close()
83
	return f.Write(file, opts...)
J
Josh Fyne 已提交
84 85
}

86 87 88
// Close closes and cleanup the open temporary file for the spreadsheet.
func (f *File) Close() error {
	var err error
89 90 91 92 93
	if f.sharedStringTemp != nil {
		if err := f.sharedStringTemp.Close(); err != nil {
			return err
		}
	}
94 95 96 97 98 99
	f.tempFiles.Range(func(k, v interface{}) bool {
		if err = os.Remove(v.(string)); err != nil {
			return false
		}
		return true
	})
100 101 102
	for _, stream := range f.streams {
		_ = stream.rawData.Close()
	}
103 104 105
	return err
}

xurime's avatar
xurime 已提交
106
// Write provides a function to write to an io.Writer.
107 108
func (f *File) Write(w io.Writer, opts ...Options) error {
	_, err := f.WriteTo(w, opts...)
109 110 111 112
	return err
}

// WriteTo implements io.WriterTo to write the file.
113 114 115 116 117
func (f *File) WriteTo(w io.Writer, opts ...Options) (int64, error) {
	for i := range opts {
		f.options = &opts[i]
	}
	if len(f.Path) != 0 {
118
		contentType, ok := supportedContentTypes[strings.ToLower(filepath.Ext(f.Path))]
119 120 121
		if !ok {
			return 0, ErrWorkbookFileFormat
		}
122 123 124
		if err := f.setContentTypePartProjectExtensions(contentType); err != nil {
			return 0, err
		}
125
	}
126 127 128 129 130 131 132 133
	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 {
134 135
		return 0, err
	}
136
	return 0, nil
137 138
}

xurime's avatar
xurime 已提交
139 140
// 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.
141
func (f *File) WriteToBuffer() (*bytes.Buffer, error) {
xurime's avatar
xurime 已提交
142
	buf := new(bytes.Buffer)
J
Josh Fyne 已提交
143
	zw := zip.NewWriter(buf)
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167

	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 {
xurime's avatar
xurime 已提交
168
		_ = zw.Close()
169 170 171 172 173 174 175
		return err
	}
	return zw.Close()
}

// writeToZip provides a function to write to zip.Writer
func (f *File) writeToZip(zw *zip.Writer) error {
176 177
	f.calcChainWriter()
	f.commentsWriter()
xurime's avatar
xurime 已提交
178
	f.contentTypesWriter()
179
	f.drawingsWriter()
180
	f.volatileDepsWriter()
181
	f.vmlDrawingWriter()
182 183
	f.workBookWriter()
	f.workSheetWriter()
xurime's avatar
xurime 已提交
184
	f.relsWriter()
185
	_ = f.sharedStringsLoader()
xurime's avatar
xurime 已提交
186
	f.sharedStringsWriter()
187
	f.styleSheetWriter()
188
	f.themeWriter()
189

190 191 192
	for path, stream := range f.streams {
		fi, err := zw.Create(path)
		if err != nil {
193
			return err
194 195
		}
		var from io.Reader
196
		if from, err = stream.rawData.Reader(); err != nil {
xurime's avatar
xurime 已提交
197
			_ = stream.rawData.Close()
198
			return err
199
		}
200
		if _, err = io.Copy(fi, from); err != nil {
201
			return err
202 203
		}
	}
204 205 206 207
	var (
		err              error
		files, tempFiles []string
	)
208 209 210 211
	f.Pkg.Range(func(path, content interface{}) bool {
		if _, ok := f.streams[path.(string)]; ok {
			return true
		}
212 213 214 215 216
		files = append(files, path.(string))
		return true
	})
	sort.Strings(files)
	for _, path := range files {
217
		var fi io.Writer
218 219
		if fi, err = zw.Create(path); err != nil {
			break
xurime's avatar
xurime 已提交
220
		}
221
		content, _ := f.Pkg.Load(path)
222
		_, err = fi.Write(content.([]byte))
223
	}
224
	f.tempFiles.Range(func(path, content interface{}) bool {
225 226 227
		if _, ok := f.Pkg.Load(path); ok {
			return true
		}
228
		tempFiles = append(tempFiles, path.(string))
229 230
		return true
	})
231 232 233 234 235 236 237 238
	sort.Strings(tempFiles)
	for _, path := range tempFiles {
		var fi io.Writer
		if fi, err = zw.Create(path); err != nil {
			break
		}
		_, err = fi.Write(f.readBytes(path))
	}
239
	return err
xurime's avatar
xurime 已提交
240
}