excelize.go 11.3 KB
Newer Older
xurime's avatar
xurime 已提交
1
// Copyright 2016 - 2021 The excelize Authors. All rights reserved. Use of
xurime's avatar
xurime 已提交
2 3
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
xurime's avatar
xurime 已提交
4

xurime's avatar
xurime 已提交
5
// Package excelize providing a set of functions that allow you to write to
6
// and read from XLSX / XLSM / XLTM files. Supports reading and writing
R
Ray 已提交
7
// spreadsheet documents generated by Microsoft Excel™ 2007 and later. Supports
8 9
// complex components by high compatibility, and provided streaming API for
// generating or reading data from a worksheet with huge amounts of data. This
10
// library needs Go version 1.15 or later.
xurime's avatar
xurime 已提交
11 12
//
// See https://xuri.me/excelize for more information about this package.
xurime's avatar
xurime 已提交
13 14 15 16
package excelize

import (
	"archive/zip"
17
	"bytes"
xurime's avatar
xurime 已提交
18
	"encoding/xml"
xurime's avatar
xurime 已提交
19
	"fmt"
J
Josh Fyne 已提交
20 21 22
	"io"
	"io/ioutil"
	"os"
23
	"path"
xurime's avatar
xurime 已提交
24
	"path/filepath"
xurime's avatar
xurime 已提交
25
	"strconv"
26
	"strings"
27
	"sync"
28 29

	"golang.org/x/net/html/charset"
xurime's avatar
xurime 已提交
30 31
)

32
// File define a populated spreadsheet file struct.
33
type File struct {
xurime's avatar
xurime 已提交
34
	sync.Mutex
xurime's avatar
xurime 已提交
35
	options          *Options
36
	xmlAttr          map[string][]xml.Attr
37 38
	checked          map[string]bool
	sheetMap         map[string]string
39
	streams          map[string]*StreamWriter
40 41 42
	CalcChain        *xlsxCalcChain
	Comments         map[string]*xlsxComments
	ContentTypes     *xlsxTypes
43
	Drawings         sync.Map
44 45
	Path             string
	SharedStrings    *xlsxSST
46
	sharedStringsMap map[string]int
xurime's avatar
xurime 已提交
47
	Sheet            sync.Map
48 49 50 51 52 53
	SheetCount       int
	Styles           *xlsxStyleSheet
	Theme            *xlsxTheme
	DecodeVMLDrawing map[string]*decodeVmlDrawing
	VMLDrawing       map[string]*vmlDrawing
	WorkBook         *xlsxWorkbook
54
	Relationships    sync.Map
55
	Pkg              sync.Map
56
	CharsetReader    charsetTranscoderFn
xurime's avatar
xurime 已提交
57 58
}

59 60
type charsetTranscoderFn func(charset string, input io.Reader) (rdr io.Reader, err error)

61 62
// Options define the options for open spreadsheet.
type Options struct {
xurime's avatar
xurime 已提交
63 64
	Password       string
	UnzipSizeLimit int64
65 66
}

xurime's avatar
xurime 已提交
67 68 69
// OpenFile take the name of an spreadsheet file and returns a populated
// spreadsheet file struct for it. For example, open spreadsheet with
// password protection:
70 71 72 73 74 75
//
//    f, err := excelize.OpenFile("Book1.xlsx", excelize.Options{Password: "password"})
//    if err != nil {
//        return
//    }
//
xurime's avatar
xurime 已提交
76 77 78 79 80 81
// Note that the excelize just support decrypt and not support encrypt
// currently, the spreadsheet saved by Save and SaveAs will be without
// password unprotected.
//
// UnzipSizeLimit specified the unzip size limit in bytes on open the
// spreadsheet, the default size limit is 16GB.
82
func OpenFile(filename string, opt ...Options) (*File, error) {
xurime's avatar
xurime 已提交
83
	file, err := os.Open(filepath.Clean(filename))
84
	if err != nil {
J
Josh Fyne 已提交
85 86
		return nil, err
	}
J
Josh Fyne 已提交
87
	defer file.Close()
xurime's avatar
xurime 已提交
88
	f, err := OpenReader(file, opt...)
J
Josh Fyne 已提交
89 90 91 92 93
	if err != nil {
		return nil, err
	}
	f.Path = filename
	return f, nil
J
Josh Fyne 已提交
94 95
}

96
// newFile is object builder
97 98
func newFile() *File {
	return &File{
xurime's avatar
xurime 已提交
99
		options:          &Options{UnzipSizeLimit: UnzipSizeLimit},
100
		xmlAttr:          make(map[string][]xml.Attr),
101 102 103
		checked:          make(map[string]bool),
		sheetMap:         make(map[string]string),
		Comments:         make(map[string]*xlsxComments),
104
		Drawings:         sync.Map{},
105
		sharedStringsMap: make(map[string]int),
106
		Sheet:            sync.Map{},
107 108
		DecodeVMLDrawing: make(map[string]*decodeVmlDrawing),
		VMLDrawing:       make(map[string]*vmlDrawing),
109
		Relationships:    sync.Map{},
110 111 112 113
		CharsetReader:    charset.NewReaderLabel,
	}
}

114 115
// OpenReader read data stream from io.Reader and return a populated
// spreadsheet file.
116
func OpenReader(r io.Reader, opt ...Options) (*File, error) {
J
Josh Fyne 已提交
117
	b, err := ioutil.ReadAll(r)
J
Josh Fyne 已提交
118 119 120
	if err != nil {
		return nil, err
	}
xurime's avatar
xurime 已提交
121
	f := newFile()
xurime's avatar
xurime 已提交
122 123 124 125
	for i := range opt {
		f.options = &opt[i]
		if f.options.UnzipSizeLimit == 0 {
			f.options.UnzipSizeLimit = UnzipSizeLimit
126
		}
xurime's avatar
xurime 已提交
127 128
	}
	if bytes.Contains(b, oleIdentifier) {
xurime's avatar
xurime 已提交
129
		b, err = Decrypt(b, f.options)
130 131
		if err != nil {
			return nil, fmt.Errorf("decrypted file failed")
132
		}
133 134 135
	}
	zr, err := zip.NewReader(bytes.NewReader(b), int64(len(b)))
	if err != nil {
J
Josh Fyne 已提交
136 137
		return nil, err
	}
xurime's avatar
xurime 已提交
138
	file, sheetCount, err := ReadZipReader(zr, f.options)
J
Josh Fyne 已提交
139 140
	if err != nil {
		return nil, err
xurime's avatar
xurime 已提交
141
	}
142 143 144 145
	f.SheetCount = sheetCount
	for k, v := range file {
		f.Pkg.Store(k, v)
	}
146
	f.CalcChain = f.calcChainReader()
wing2life's avatar
wing2life 已提交
147 148
	f.sheetMap = f.getSheetMap()
	f.Styles = f.stylesReader()
xurime's avatar
xurime 已提交
149
	f.Theme = f.themeReader()
wing2life's avatar
wing2life 已提交
150
	return f, nil
xurime's avatar
xurime 已提交
151 152
}

153 154
// CharsetTranscoder Set user defined codepage transcoder function for open
// XLSX from non UTF-8 encoding.
155 156
func (f *File) CharsetTranscoder(fn charsetTranscoderFn) *File { f.CharsetReader = fn; return f }

157
// Creates new XML decoder with charset reader.
158 159 160 161 162 163
func (f *File) xmlNewDecoder(rdr io.Reader) (ret *xml.Decoder) {
	ret = xml.NewDecoder(rdr)
	ret.CharsetReader = f.CharsetReader
	return
}

xurime's avatar
xurime 已提交
164
// setDefaultTimeStyle provides a function to set default numbers format for
165 166
// time.Time type cell value by given worksheet name, cell coordinates and
// number format code.
167 168 169 170 171 172
func (f *File) setDefaultTimeStyle(sheet, axis string, format int) error {
	s, err := f.GetCellStyle(sheet, axis)
	if err != nil {
		return err
	}
	if s == 0 {
173
		style, _ := f.NewStyle(&Style{NumFmt: format})
174
		err = f.SetCellStyle(sheet, axis, axis, style)
175
	}
176
	return err
177 178
}

xurime's avatar
xurime 已提交
179 180
// workSheetReader provides a function to get the pointer to the structure
// after deserialization by given worksheet name.
181
func (f *File) workSheetReader(sheet string) (ws *xlsxWorksheet, err error) {
182 183
	f.Lock()
	defer f.Unlock()
184 185 186 187 188 189 190
	var (
		name string
		ok   bool
	)
	if name, ok = f.sheetMap[trimSheetName(sheet)]; !ok {
		err = fmt.Errorf("sheet %s is not exist", sheet)
		return
191
	}
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
	if worksheet, ok := f.Sheet.Load(name); ok && worksheet != nil {
		ws = worksheet.(*xlsxWorksheet)
		return
	}
	if strings.HasPrefix(name, "xl/chartsheets") {
		err = fmt.Errorf("sheet %s is chart sheet", sheet)
		return
	}
	ws = new(xlsxWorksheet)
	if _, ok := f.xmlAttr[name]; !ok {
		d := f.xmlNewDecoder(bytes.NewReader(namespaceStrictToTransitional(f.readXML(name))))
		f.xmlAttr[name] = append(f.xmlAttr[name], getRootElement(d)...)
	}
	if err = f.xmlNewDecoder(bytes.NewReader(namespaceStrictToTransitional(f.readXML(name)))).
		Decode(ws); err != nil && err != io.EOF {
		err = fmt.Errorf("xml decode error: %s", err)
		return
	}
	err = nil
	if f.checked == nil {
		f.checked = make(map[string]bool)
	}
	if ok = f.checked[name]; !ok {
		checkSheet(ws)
		if err = checkRow(ws); err != nil {
217 218
			return
		}
219
		f.checked[name] = true
220
	}
221
	f.Sheet.Store(name, ws)
222
	return
xurime's avatar
xurime 已提交
223
}
224

xurime's avatar
xurime 已提交
225
// checkSheet provides a function to fill each row element and make that is
226
// continuous in a worksheet of XML.
227
func checkSheet(ws *xlsxWorksheet) {
228
	var row int
229
	for _, r := range ws.SheetData.Row {
230 231 232
		if r.R != 0 && r.R > row {
			row = r.R
			continue
233
		}
234 235 236
		if r.R != row {
			row++
		}
237
	}
H
Harris 已提交
238
	sheetData := xlsxSheetData{Row: make([]xlsxRow, row)}
239
	row = 0
240
	for _, r := range ws.SheetData.Row {
241
		if r.R == row && row > 0 {
242 243 244
			sheetData.Row[r.R-1].C = append(sheetData.Row[r.R-1].C, r.C...)
			continue
		}
245 246 247 248 249 250 251 252
		if r.R != 0 {
			sheetData.Row[r.R-1] = r
			row = r.R
			continue
		}
		row++
		r.R = row
		sheetData.Row[row-1] = r
253
	}
H
Harris 已提交
254 255
	for i := 1; i <= row; i++ {
		sheetData.Row[i-1].R = i
256
	}
257
	ws.SheetData = sheetData
xurime's avatar
xurime 已提交
258 259
}

xurime's avatar
xurime 已提交
260 261 262
// addRels provides a function to add relationships by given XML path,
// relationship type, target and target mode.
func (f *File) addRels(relPath, relType, target, targetMode string) int {
263 264 265
	var uniqPart = map[string]string{
		SourceRelationshipSharedStrings: "/xl/sharedStrings.xml",
	}
xurime's avatar
xurime 已提交
266 267 268 269
	rels := f.relsReader(relPath)
	if rels == nil {
		rels = &xlsxRelationships{}
	}
xurime's avatar
xurime 已提交
270 271
	rels.Lock()
	defer rels.Unlock()
272
	var rID int
273
	for idx, rel := range rels.Relationships {
274 275 276 277
		ID, _ := strconv.Atoi(strings.TrimPrefix(rel.ID, "rId"))
		if ID > rID {
			rID = ID
		}
278 279 280 281 282 283
		if relType == rel.Type {
			if partName, ok := uniqPart[rel.Type]; ok {
				rels.Relationships[idx].Target = partName
				return rID
			}
		}
284 285
	}
	rID++
xurime's avatar
xurime 已提交
286 287 288 289 290 291 292 293 294
	var ID bytes.Buffer
	ID.WriteString("rId")
	ID.WriteString(strconv.Itoa(rID))
	rels.Relationships = append(rels.Relationships, xlsxRelationship{
		ID:         ID.String(),
		Type:       relType,
		Target:     target,
		TargetMode: targetMode,
	})
295
	f.Relationships.Store(relPath, rels)
xurime's avatar
xurime 已提交
296 297 298
	return rID
}

299 300
// UpdateLinkedValue fix linked values within a spreadsheet are not updating in
// Office Excel 2007 and 2010. This function will be remove value tag when met a
301
// cell have a linked value. Reference
302
// https://social.technet.microsoft.com/Forums/office/en-US/e16bae1f-6a2c-4325-8013-e989a3479066/excel-2010-linked-cells-not-updating
303 304 305 306 307 308
//
// Notice: after open XLSX file Excel will be update linked value and generate
// new value and will prompt save file or not.
//
// For example:
//
309 310 311 312 313 314
//    <row r="19" spans="2:2">
//        <c r="B19">
//            <f>SUM(Sheet2!D2,Sheet2!D11)</f>
//            <v>100</v>
//         </c>
//    </row>
315 316 317
//
// to
//
318 319 320 321 322
//    <row r="19" spans="2:2">
//        <c r="B19">
//            <f>SUM(Sheet2!D2,Sheet2!D11)</f>
//        </c>
//    </row>
323
//
xurime's avatar
xurime 已提交
324
func (f *File) UpdateLinkedValue() error {
325 326 327
	wb := f.workbookReader()
	// recalculate formulas
	wb.CalcPr = nil
328
	for _, name := range f.GetSheetList() {
xurime's avatar
xurime 已提交
329
		ws, err := f.workSheetReader(name)
xurime's avatar
xurime 已提交
330
		if err != nil {
331 332 333
			if err.Error() == fmt.Sprintf("sheet %s is chart sheet", trimSheetName(name)) {
				continue
			}
xurime's avatar
xurime 已提交
334 335
			return err
		}
xurime's avatar
xurime 已提交
336 337
		for indexR := range ws.SheetData.Row {
			for indexC, col := range ws.SheetData.Row[indexR].C {
338
				if col.F != nil && col.V != "" {
xurime's avatar
xurime 已提交
339 340
					ws.SheetData.Row[indexR].C[indexC].V = ""
					ws.SheetData.Row[indexR].C[indexC].T = ""
341 342 343 344
				}
			}
		}
	}
xurime's avatar
xurime 已提交
345
	return nil
346
}
347 348 349 350

// AddVBAProject provides the method to add vbaProject.bin file which contains
// functions and/or macros. The file extension should be .xlsm. For example:
//
351
//    if err := f.SetSheetPrOptions("Sheet1", excelize.CodeName("Sheet1")); err != nil {
xurime's avatar
xurime 已提交
352
//        fmt.Println(err)
353
//    }
354
//    if err := f.AddVBAProject("vbaProject.bin"); err != nil {
xurime's avatar
xurime 已提交
355
//        fmt.Println(err)
356
//    }
357
//    if err := f.SaveAs("macros.xlsm"); err != nil {
xurime's avatar
xurime 已提交
358
//        fmt.Println(err)
359 360 361 362 363 364
//    }
//
func (f *File) AddVBAProject(bin string) error {
	var err error
	// Check vbaProject.bin exists first.
	if _, err = os.Stat(bin); os.IsNotExist(err) {
365
		return fmt.Errorf("stat %s: no such file or directory", bin)
366 367
	}
	if path.Ext(bin) != ".bin" {
368
		return ErrAddVBAProject
369 370
	}
	f.setContentTypePartVBAProjectExtensions()
371
	wb := f.relsReader(f.getWorkbookRelsPath())
xurime's avatar
xurime 已提交
372 373
	wb.Lock()
	defer wb.Unlock()
374 375 376 377 378 379 380 381 382 383 384 385 386 387
	var rID int
	var ok bool
	for _, rel := range wb.Relationships {
		if rel.Target == "vbaProject.bin" && rel.Type == SourceRelationshipVBAProject {
			ok = true
			continue
		}
		t, _ := strconv.Atoi(strings.TrimPrefix(rel.ID, "rId"))
		if t > rID {
			rID = t
		}
	}
	rID++
	if !ok {
xurime's avatar
xurime 已提交
388
		wb.Relationships = append(wb.Relationships, xlsxRelationship{
389 390 391 392 393
			ID:     "rId" + strconv.Itoa(rID),
			Target: "vbaProject.bin",
			Type:   SourceRelationshipVBAProject,
		})
	}
xurime's avatar
xurime 已提交
394
	file, _ := ioutil.ReadFile(filepath.Clean(bin))
395
	f.Pkg.Store("xl/vbaProject.bin", file)
396 397 398 399 400 401 402 403
	return err
}

// setContentTypePartVBAProjectExtensions provides a function to set the
// content type for relationship parts and the main document part.
func (f *File) setContentTypePartVBAProjectExtensions() {
	var ok bool
	content := f.contentTypesReader()
xurime's avatar
xurime 已提交
404 405
	content.Lock()
	defer content.Unlock()
406 407 408 409 410 411 412
	for _, v := range content.Defaults {
		if v.Extension == "bin" {
			ok = true
		}
	}
	for idx, o := range content.Overrides {
		if o.PartName == "/xl/workbook.xml" {
413
			content.Overrides[idx].ContentType = ContentTypeMacro
414 415 416 417 418
		}
	}
	if !ok {
		content.Defaults = append(content.Defaults, xlsxDefault{
			Extension:   "bin",
419
			ContentType: ContentTypeVBA,
420 421 422
		})
	}
}