2023-01-02 11:47:31 +08:00
|
|
|
// Copyright 2016 - 2023 The excelize Authors. All rights reserved. Use of
|
2018-09-14 00:44:23 +08:00
|
|
|
// this source code is governed by a BSD-style license that can be found in
|
|
|
|
// the LICENSE file.
|
|
|
|
//
|
2022-02-17 00:09:11 +08:00
|
|
|
// 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
|
2023-01-02 11:47:31 +08:00
|
|
|
// data. This library needs Go version 1.16 or later.
|
2018-09-14 00:58:48 +08:00
|
|
|
|
2016-08-30 11:51:31 +08:00
|
|
|
package excelize
|
|
|
|
|
|
|
|
import (
|
|
|
|
"archive/zip"
|
|
|
|
"bytes"
|
2020-05-03 18:44:43 +08:00
|
|
|
"container/list"
|
2020-07-18 15:15:16 +08:00
|
|
|
"encoding/xml"
|
Huge refactorig for consistent col/row numbering (#356)
* Huge refactorig for consistent col/row numbering
Started from simply changing ToALphaString()/TitleToNumber() logic and related fixes.
But have to go deeper, do fixes, after do related fixes and again and again.
Major improvements:
1. Tests made stronger again (But still be weak).
2. "Empty" returns for incorrect input replaces with panic.
3. Check for correct col/row/cell naming & addressing by default.
4. Removed huge amount of duplicated code.
5. Removed ToALphaString(), TitleToNumber() and it helpers functions at all,
and replaced with SplitCellName(), JoinCellName(), ColumnNameToNumber(), ColumnNumberToName(), CellNameToCoordinates(), CoordinatesToCellName().
6. Minor fixes for internal variable naming for code readability (ex. col, row for input params, colIdx, rowIdx for slice indexes etc).
* Formatting fixes
2019-03-20 00:14:41 +08:00
|
|
|
"fmt"
|
2016-08-30 11:51:31 +08:00
|
|
|
"io"
|
2022-09-28 00:04:17 +08:00
|
|
|
"math/big"
|
2021-09-18 23:20:24 +08:00
|
|
|
"os"
|
2021-06-11 22:48:37 +08:00
|
|
|
"regexp"
|
2018-11-02 23:08:31 +08:00
|
|
|
"strconv"
|
|
|
|
"strings"
|
2016-08-30 11:51:31 +08:00
|
|
|
)
|
|
|
|
|
2021-09-18 23:20:24 +08:00
|
|
|
// ReadZipReader extract spreadsheet with given options.
|
|
|
|
func (f *File) ReadZipReader(r *zip.Reader) (map[string][]byte, int, error) {
|
2021-08-15 00:06:40 +08:00
|
|
|
var (
|
|
|
|
err error
|
|
|
|
docPart = map[string]string{
|
2021-12-27 23:34:14 +08:00
|
|
|
"[content_types].xml": defaultXMLPathContentTypes,
|
2022-01-09 00:20:42 +08:00
|
|
|
"xl/sharedstrings.xml": defaultXMLPathSharedStrings,
|
2021-08-15 00:06:40 +08:00
|
|
|
}
|
|
|
|
fileList = make(map[string][]byte, len(r.File))
|
|
|
|
worksheets int
|
|
|
|
unzipSize int64
|
|
|
|
)
|
2016-08-30 11:51:31 +08:00
|
|
|
for _, v := range r.File {
|
2021-09-18 23:20:24 +08:00
|
|
|
fileSize := v.FileInfo().Size()
|
|
|
|
unzipSize += fileSize
|
|
|
|
if unzipSize > f.options.UnzipSizeLimit {
|
|
|
|
return fileList, worksheets, newUnzipSizeLimitError(f.options.UnzipSizeLimit)
|
2021-08-15 00:06:40 +08:00
|
|
|
}
|
2022-06-12 00:19:12 +08:00
|
|
|
fileName := strings.ReplaceAll(v.Name, "\\", "/")
|
2021-02-27 00:03:46 +08:00
|
|
|
if partName, ok := docPart[strings.ToLower(fileName)]; ok {
|
2020-07-09 01:24:11 +08:00
|
|
|
fileName = partName
|
|
|
|
}
|
2022-01-09 00:20:42 +08:00
|
|
|
if strings.EqualFold(fileName, defaultXMLPathSharedStrings) && fileSize > f.options.UnzipXMLSizeLimit {
|
2021-12-27 23:34:14 +08:00
|
|
|
if tempFile, err := f.unzipToTemp(v); err == nil {
|
|
|
|
f.tempFiles.Store(fileName, tempFile)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
}
|
2023-07-28 00:24:08 +08:00
|
|
|
if strings.HasPrefix(strings.ToLower(fileName), "xl/worksheets/sheet") {
|
2019-10-24 22:14:33 +08:00
|
|
|
worksheets++
|
2021-12-27 23:34:14 +08:00
|
|
|
if fileSize > f.options.UnzipXMLSizeLimit && !v.FileInfo().IsDir() {
|
2021-09-18 23:20:24 +08:00
|
|
|
if tempFile, err := f.unzipToTemp(v); err == nil {
|
|
|
|
f.tempFiles.Store(fileName, tempFile)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if fileList[fileName], err = readFile(v); err != nil {
|
|
|
|
return nil, 0, err
|
2016-09-06 21:20:24 +08:00
|
|
|
}
|
2016-08-30 11:51:31 +08:00
|
|
|
}
|
2016-09-06 21:20:24 +08:00
|
|
|
return fileList, worksheets, nil
|
2016-08-30 11:51:31 +08:00
|
|
|
}
|
|
|
|
|
2021-09-18 23:20:24 +08:00
|
|
|
// unzipToTemp unzip the zip entity to the system temporary directory and
|
|
|
|
// returned the unzipped file path.
|
|
|
|
func (f *File) unzipToTemp(zipFile *zip.File) (string, error) {
|
2022-10-13 00:02:53 +08:00
|
|
|
tmp, err := os.CreateTemp(os.TempDir(), "excelize-")
|
2021-09-18 23:20:24 +08:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
rc, err := zipFile.Open()
|
|
|
|
if err != nil {
|
|
|
|
return tmp.Name(), err
|
|
|
|
}
|
2022-03-24 00:19:30 +08:00
|
|
|
if _, err = io.Copy(tmp, rc); err != nil {
|
|
|
|
return tmp.Name(), err
|
|
|
|
}
|
|
|
|
if err = rc.Close(); err != nil {
|
|
|
|
return tmp.Name(), err
|
|
|
|
}
|
|
|
|
return tmp.Name(), tmp.Close()
|
2021-09-18 23:20:24 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// readXML provides a function to read XML content as bytes.
|
2018-05-07 16:12:51 +08:00
|
|
|
func (f *File) readXML(name string) []byte {
|
2021-07-05 00:03:56 +08:00
|
|
|
if content, _ := f.Pkg.Load(name); content != nil {
|
|
|
|
return content.([]byte)
|
2016-08-30 11:51:31 +08:00
|
|
|
}
|
2021-04-08 00:50:59 +08:00
|
|
|
if content, ok := f.streams[name]; ok {
|
|
|
|
return content.rawData.buf.Bytes()
|
|
|
|
}
|
2018-05-07 16:12:51 +08:00
|
|
|
return []byte{}
|
2016-08-30 11:51:31 +08:00
|
|
|
}
|
|
|
|
|
2021-09-18 23:20:24 +08:00
|
|
|
// readBytes read file as bytes by given path.
|
|
|
|
func (f *File) readBytes(name string) []byte {
|
|
|
|
content := f.readXML(name)
|
|
|
|
if len(content) != 0 {
|
|
|
|
return content
|
|
|
|
}
|
|
|
|
file, err := f.readTemp(name)
|
|
|
|
if err != nil {
|
|
|
|
return content
|
|
|
|
}
|
2022-10-13 00:02:53 +08:00
|
|
|
content, _ = io.ReadAll(file)
|
2021-09-18 23:20:24 +08:00
|
|
|
f.Pkg.Store(name, content)
|
2022-03-24 00:19:30 +08:00
|
|
|
_ = file.Close()
|
2021-09-18 23:20:24 +08:00
|
|
|
return content
|
|
|
|
}
|
|
|
|
|
|
|
|
// readTemp read file from system temporary directory by given path.
|
|
|
|
func (f *File) readTemp(name string) (file *os.File, err error) {
|
|
|
|
path, ok := f.tempFiles.Load(name)
|
|
|
|
if !ok {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
file, err = os.Open(path.(string))
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2018-08-06 10:21:24 +08:00
|
|
|
// saveFileList provides a function to update given file content in file list
|
2021-08-15 00:06:40 +08:00
|
|
|
// of spreadsheet.
|
2018-05-07 16:12:51 +08:00
|
|
|
func (f *File) saveFileList(name string, content []byte) {
|
2021-12-27 23:34:14 +08:00
|
|
|
f.Pkg.Store(name, append([]byte(xml.Header), content...))
|
2016-08-30 11:51:31 +08:00
|
|
|
}
|
|
|
|
|
2022-04-04 00:21:33 +08:00
|
|
|
// Read file content as string in an archive file.
|
2020-05-23 12:51:46 +08:00
|
|
|
func readFile(file *zip.File) ([]byte, error) {
|
2016-08-30 11:51:31 +08:00
|
|
|
rc, err := file.Open()
|
|
|
|
if err != nil {
|
2020-05-23 12:51:46 +08:00
|
|
|
return nil, err
|
2016-08-30 11:51:31 +08:00
|
|
|
}
|
2019-10-24 22:14:33 +08:00
|
|
|
dat := make([]byte, 0, file.FileInfo().Size())
|
|
|
|
buff := bytes.NewBuffer(dat)
|
2018-05-27 11:25:55 +08:00
|
|
|
_, _ = io.Copy(buff, rc)
|
2021-08-15 00:06:40 +08:00
|
|
|
return buff.Bytes(), rc.Close()
|
2016-08-30 11:51:31 +08:00
|
|
|
}
|
|
|
|
|
Huge refactorig for consistent col/row numbering (#356)
* Huge refactorig for consistent col/row numbering
Started from simply changing ToALphaString()/TitleToNumber() logic and related fixes.
But have to go deeper, do fixes, after do related fixes and again and again.
Major improvements:
1. Tests made stronger again (But still be weak).
2. "Empty" returns for incorrect input replaces with panic.
3. Check for correct col/row/cell naming & addressing by default.
4. Removed huge amount of duplicated code.
5. Removed ToALphaString(), TitleToNumber() and it helpers functions at all,
and replaced with SplitCellName(), JoinCellName(), ColumnNameToNumber(), ColumnNumberToName(), CellNameToCoordinates(), CoordinatesToCellName().
6. Minor fixes for internal variable naming for code readability (ex. col, row for input params, colIdx, rowIdx for slice indexes etc).
* Formatting fixes
2019-03-20 00:14:41 +08:00
|
|
|
// SplitCellName splits cell name to column name and row number.
|
2017-06-26 18:44:19 +08:00
|
|
|
//
|
Huge refactorig for consistent col/row numbering (#356)
* Huge refactorig for consistent col/row numbering
Started from simply changing ToALphaString()/TitleToNumber() logic and related fixes.
But have to go deeper, do fixes, after do related fixes and again and again.
Major improvements:
1. Tests made stronger again (But still be weak).
2. "Empty" returns for incorrect input replaces with panic.
3. Check for correct col/row/cell naming & addressing by default.
4. Removed huge amount of duplicated code.
5. Removed ToALphaString(), TitleToNumber() and it helpers functions at all,
and replaced with SplitCellName(), JoinCellName(), ColumnNameToNumber(), ColumnNumberToName(), CellNameToCoordinates(), CoordinatesToCellName().
6. Minor fixes for internal variable naming for code readability (ex. col, row for input params, colIdx, rowIdx for slice indexes etc).
* Formatting fixes
2019-03-20 00:14:41 +08:00
|
|
|
// Example:
|
2017-06-26 18:44:19 +08:00
|
|
|
//
|
2022-08-13 11:21:59 +08:00
|
|
|
// excelize.SplitCellName("AK74") // return "AK", 74, nil
|
Huge refactorig for consistent col/row numbering (#356)
* Huge refactorig for consistent col/row numbering
Started from simply changing ToALphaString()/TitleToNumber() logic and related fixes.
But have to go deeper, do fixes, after do related fixes and again and again.
Major improvements:
1. Tests made stronger again (But still be weak).
2. "Empty" returns for incorrect input replaces with panic.
3. Check for correct col/row/cell naming & addressing by default.
4. Removed huge amount of duplicated code.
5. Removed ToALphaString(), TitleToNumber() and it helpers functions at all,
and replaced with SplitCellName(), JoinCellName(), ColumnNameToNumber(), ColumnNumberToName(), CellNameToCoordinates(), CoordinatesToCellName().
6. Minor fixes for internal variable naming for code readability (ex. col, row for input params, colIdx, rowIdx for slice indexes etc).
* Formatting fixes
2019-03-20 00:14:41 +08:00
|
|
|
func SplitCellName(cell string) (string, int, error) {
|
|
|
|
alpha := func(r rune) bool {
|
2021-08-15 01:19:49 +08:00
|
|
|
return ('A' <= r && r <= 'Z') || ('a' <= r && r <= 'z') || (r == 36)
|
Huge refactorig for consistent col/row numbering (#356)
* Huge refactorig for consistent col/row numbering
Started from simply changing ToALphaString()/TitleToNumber() logic and related fixes.
But have to go deeper, do fixes, after do related fixes and again and again.
Major improvements:
1. Tests made stronger again (But still be weak).
2. "Empty" returns for incorrect input replaces with panic.
3. Check for correct col/row/cell naming & addressing by default.
4. Removed huge amount of duplicated code.
5. Removed ToALphaString(), TitleToNumber() and it helpers functions at all,
and replaced with SplitCellName(), JoinCellName(), ColumnNameToNumber(), ColumnNumberToName(), CellNameToCoordinates(), CoordinatesToCellName().
6. Minor fixes for internal variable naming for code readability (ex. col, row for input params, colIdx, rowIdx for slice indexes etc).
* Formatting fixes
2019-03-20 00:14:41 +08:00
|
|
|
}
|
|
|
|
if strings.IndexFunc(cell, alpha) == 0 {
|
|
|
|
i := strings.LastIndexFunc(cell, alpha)
|
|
|
|
if i >= 0 && i < len(cell)-1 {
|
2022-04-04 00:21:33 +08:00
|
|
|
col, rowStr := strings.ReplaceAll(cell[:i+1], "$", ""), cell[i+1:]
|
|
|
|
if row, err := strconv.Atoi(rowStr); err == nil && row > 0 {
|
Huge refactorig for consistent col/row numbering (#356)
* Huge refactorig for consistent col/row numbering
Started from simply changing ToALphaString()/TitleToNumber() logic and related fixes.
But have to go deeper, do fixes, after do related fixes and again and again.
Major improvements:
1. Tests made stronger again (But still be weak).
2. "Empty" returns for incorrect input replaces with panic.
3. Check for correct col/row/cell naming & addressing by default.
4. Removed huge amount of duplicated code.
5. Removed ToALphaString(), TitleToNumber() and it helpers functions at all,
and replaced with SplitCellName(), JoinCellName(), ColumnNameToNumber(), ColumnNumberToName(), CellNameToCoordinates(), CoordinatesToCellName().
6. Minor fixes for internal variable naming for code readability (ex. col, row for input params, colIdx, rowIdx for slice indexes etc).
* Formatting fixes
2019-03-20 00:14:41 +08:00
|
|
|
return col, row, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return "", -1, newInvalidCellNameError(cell)
|
|
|
|
}
|
|
|
|
|
2019-04-20 14:57:50 +08:00
|
|
|
// JoinCellName joins cell name from column name and row number.
|
Huge refactorig for consistent col/row numbering (#356)
* Huge refactorig for consistent col/row numbering
Started from simply changing ToALphaString()/TitleToNumber() logic and related fixes.
But have to go deeper, do fixes, after do related fixes and again and again.
Major improvements:
1. Tests made stronger again (But still be weak).
2. "Empty" returns for incorrect input replaces with panic.
3. Check for correct col/row/cell naming & addressing by default.
4. Removed huge amount of duplicated code.
5. Removed ToALphaString(), TitleToNumber() and it helpers functions at all,
and replaced with SplitCellName(), JoinCellName(), ColumnNameToNumber(), ColumnNumberToName(), CellNameToCoordinates(), CoordinatesToCellName().
6. Minor fixes for internal variable naming for code readability (ex. col, row for input params, colIdx, rowIdx for slice indexes etc).
* Formatting fixes
2019-03-20 00:14:41 +08:00
|
|
|
func JoinCellName(col string, row int) (string, error) {
|
|
|
|
normCol := strings.Map(func(rune rune) rune {
|
|
|
|
switch {
|
|
|
|
case 'A' <= rune && rune <= 'Z':
|
|
|
|
return rune
|
|
|
|
case 'a' <= rune && rune <= 'z':
|
|
|
|
return rune - 32
|
|
|
|
}
|
|
|
|
return -1
|
|
|
|
}, col)
|
|
|
|
if len(col) == 0 || len(col) != len(normCol) {
|
|
|
|
return "", newInvalidColumnNameError(col)
|
2016-08-30 11:51:31 +08:00
|
|
|
}
|
Huge refactorig for consistent col/row numbering (#356)
* Huge refactorig for consistent col/row numbering
Started from simply changing ToALphaString()/TitleToNumber() logic and related fixes.
But have to go deeper, do fixes, after do related fixes and again and again.
Major improvements:
1. Tests made stronger again (But still be weak).
2. "Empty" returns for incorrect input replaces with panic.
3. Check for correct col/row/cell naming & addressing by default.
4. Removed huge amount of duplicated code.
5. Removed ToALphaString(), TitleToNumber() and it helpers functions at all,
and replaced with SplitCellName(), JoinCellName(), ColumnNameToNumber(), ColumnNumberToName(), CellNameToCoordinates(), CoordinatesToCellName().
6. Minor fixes for internal variable naming for code readability (ex. col, row for input params, colIdx, rowIdx for slice indexes etc).
* Formatting fixes
2019-03-20 00:14:41 +08:00
|
|
|
if row < 1 {
|
|
|
|
return "", newInvalidRowNumberError(row)
|
2016-08-30 11:51:31 +08:00
|
|
|
}
|
2020-04-02 00:41:14 +08:00
|
|
|
return normCol + strconv.Itoa(row), nil
|
2016-08-30 11:51:31 +08:00
|
|
|
}
|
|
|
|
|
2019-04-20 14:57:50 +08:00
|
|
|
// ColumnNameToNumber provides a function to convert Excel sheet column name
|
2022-07-18 00:21:34 +08:00
|
|
|
// (case-insensitive) to int. The function returns an error if column name
|
|
|
|
// incorrect.
|
2017-06-27 17:53:06 +08:00
|
|
|
//
|
Huge refactorig for consistent col/row numbering (#356)
* Huge refactorig for consistent col/row numbering
Started from simply changing ToALphaString()/TitleToNumber() logic and related fixes.
But have to go deeper, do fixes, after do related fixes and again and again.
Major improvements:
1. Tests made stronger again (But still be weak).
2. "Empty" returns for incorrect input replaces with panic.
3. Check for correct col/row/cell naming & addressing by default.
4. Removed huge amount of duplicated code.
5. Removed ToALphaString(), TitleToNumber() and it helpers functions at all,
and replaced with SplitCellName(), JoinCellName(), ColumnNameToNumber(), ColumnNumberToName(), CellNameToCoordinates(), CoordinatesToCellName().
6. Minor fixes for internal variable naming for code readability (ex. col, row for input params, colIdx, rowIdx for slice indexes etc).
* Formatting fixes
2019-03-20 00:14:41 +08:00
|
|
|
// Example:
|
2017-06-27 17:53:06 +08:00
|
|
|
//
|
2022-08-13 11:21:59 +08:00
|
|
|
// excelize.ColumnNameToNumber("AK") // returns 37, nil
|
Huge refactorig for consistent col/row numbering (#356)
* Huge refactorig for consistent col/row numbering
Started from simply changing ToALphaString()/TitleToNumber() logic and related fixes.
But have to go deeper, do fixes, after do related fixes and again and again.
Major improvements:
1. Tests made stronger again (But still be weak).
2. "Empty" returns for incorrect input replaces with panic.
3. Check for correct col/row/cell naming & addressing by default.
4. Removed huge amount of duplicated code.
5. Removed ToALphaString(), TitleToNumber() and it helpers functions at all,
and replaced with SplitCellName(), JoinCellName(), ColumnNameToNumber(), ColumnNumberToName(), CellNameToCoordinates(), CoordinatesToCellName().
6. Minor fixes for internal variable naming for code readability (ex. col, row for input params, colIdx, rowIdx for slice indexes etc).
* Formatting fixes
2019-03-20 00:14:41 +08:00
|
|
|
func ColumnNameToNumber(name string) (int, error) {
|
|
|
|
if len(name) == 0 {
|
|
|
|
return -1, newInvalidColumnNameError(name)
|
|
|
|
}
|
|
|
|
col := 0
|
|
|
|
multi := 1
|
|
|
|
for i := len(name) - 1; i >= 0; i-- {
|
|
|
|
r := name[i]
|
|
|
|
if r >= 'A' && r <= 'Z' {
|
|
|
|
col += int(r-'A'+1) * multi
|
|
|
|
} else if r >= 'a' && r <= 'z' {
|
|
|
|
col += int(r-'a'+1) * multi
|
|
|
|
} else {
|
|
|
|
return -1, newInvalidColumnNameError(name)
|
2017-09-05 18:06:38 +08:00
|
|
|
}
|
Huge refactorig for consistent col/row numbering (#356)
* Huge refactorig for consistent col/row numbering
Started from simply changing ToALphaString()/TitleToNumber() logic and related fixes.
But have to go deeper, do fixes, after do related fixes and again and again.
Major improvements:
1. Tests made stronger again (But still be weak).
2. "Empty" returns for incorrect input replaces with panic.
3. Check for correct col/row/cell naming & addressing by default.
4. Removed huge amount of duplicated code.
5. Removed ToALphaString(), TitleToNumber() and it helpers functions at all,
and replaced with SplitCellName(), JoinCellName(), ColumnNameToNumber(), ColumnNumberToName(), CellNameToCoordinates(), CoordinatesToCellName().
6. Minor fixes for internal variable naming for code readability (ex. col, row for input params, colIdx, rowIdx for slice indexes etc).
* Formatting fixes
2019-03-20 00:14:41 +08:00
|
|
|
multi *= 26
|
2016-08-30 11:51:31 +08:00
|
|
|
}
|
2022-07-14 23:36:43 +08:00
|
|
|
if col > MaxColumns {
|
2021-05-10 00:09:24 +08:00
|
|
|
return -1, ErrColumnNumber
|
2020-05-29 00:26:40 +08:00
|
|
|
}
|
Huge refactorig for consistent col/row numbering (#356)
* Huge refactorig for consistent col/row numbering
Started from simply changing ToALphaString()/TitleToNumber() logic and related fixes.
But have to go deeper, do fixes, after do related fixes and again and again.
Major improvements:
1. Tests made stronger again (But still be weak).
2. "Empty" returns for incorrect input replaces with panic.
3. Check for correct col/row/cell naming & addressing by default.
4. Removed huge amount of duplicated code.
5. Removed ToALphaString(), TitleToNumber() and it helpers functions at all,
and replaced with SplitCellName(), JoinCellName(), ColumnNameToNumber(), ColumnNumberToName(), CellNameToCoordinates(), CoordinatesToCellName().
6. Minor fixes for internal variable naming for code readability (ex. col, row for input params, colIdx, rowIdx for slice indexes etc).
* Formatting fixes
2019-03-20 00:14:41 +08:00
|
|
|
return col, nil
|
2016-08-30 11:51:31 +08:00
|
|
|
}
|
|
|
|
|
2019-04-20 14:57:50 +08:00
|
|
|
// ColumnNumberToName provides a function to convert the integer to Excel
|
|
|
|
// sheet column title.
|
Huge refactorig for consistent col/row numbering (#356)
* Huge refactorig for consistent col/row numbering
Started from simply changing ToALphaString()/TitleToNumber() logic and related fixes.
But have to go deeper, do fixes, after do related fixes and again and again.
Major improvements:
1. Tests made stronger again (But still be weak).
2. "Empty" returns for incorrect input replaces with panic.
3. Check for correct col/row/cell naming & addressing by default.
4. Removed huge amount of duplicated code.
5. Removed ToALphaString(), TitleToNumber() and it helpers functions at all,
and replaced with SplitCellName(), JoinCellName(), ColumnNameToNumber(), ColumnNumberToName(), CellNameToCoordinates(), CoordinatesToCellName().
6. Minor fixes for internal variable naming for code readability (ex. col, row for input params, colIdx, rowIdx for slice indexes etc).
* Formatting fixes
2019-03-20 00:14:41 +08:00
|
|
|
//
|
|
|
|
// Example:
|
|
|
|
//
|
2022-08-13 11:21:59 +08:00
|
|
|
// excelize.ColumnNumberToName(37) // returns "AK", nil
|
Huge refactorig for consistent col/row numbering (#356)
* Huge refactorig for consistent col/row numbering
Started from simply changing ToALphaString()/TitleToNumber() logic and related fixes.
But have to go deeper, do fixes, after do related fixes and again and again.
Major improvements:
1. Tests made stronger again (But still be weak).
2. "Empty" returns for incorrect input replaces with panic.
3. Check for correct col/row/cell naming & addressing by default.
4. Removed huge amount of duplicated code.
5. Removed ToALphaString(), TitleToNumber() and it helpers functions at all,
and replaced with SplitCellName(), JoinCellName(), ColumnNameToNumber(), ColumnNumberToName(), CellNameToCoordinates(), CoordinatesToCellName().
6. Minor fixes for internal variable naming for code readability (ex. col, row for input params, colIdx, rowIdx for slice indexes etc).
* Formatting fixes
2019-03-20 00:14:41 +08:00
|
|
|
func ColumnNumberToName(num int) (string, error) {
|
2022-07-14 23:36:43 +08:00
|
|
|
if num < MinColumns || num > MaxColumns {
|
2021-05-10 00:09:24 +08:00
|
|
|
return "", ErrColumnNumber
|
2020-06-22 00:05:19 +08:00
|
|
|
}
|
Huge refactorig for consistent col/row numbering (#356)
* Huge refactorig for consistent col/row numbering
Started from simply changing ToALphaString()/TitleToNumber() logic and related fixes.
But have to go deeper, do fixes, after do related fixes and again and again.
Major improvements:
1. Tests made stronger again (But still be weak).
2. "Empty" returns for incorrect input replaces with panic.
3. Check for correct col/row/cell naming & addressing by default.
4. Removed huge amount of duplicated code.
5. Removed ToALphaString(), TitleToNumber() and it helpers functions at all,
and replaced with SplitCellName(), JoinCellName(), ColumnNameToNumber(), ColumnNumberToName(), CellNameToCoordinates(), CoordinatesToCellName().
6. Minor fixes for internal variable naming for code readability (ex. col, row for input params, colIdx, rowIdx for slice indexes etc).
* Formatting fixes
2019-03-20 00:14:41 +08:00
|
|
|
var col string
|
|
|
|
for num > 0 {
|
2020-08-15 00:09:50 +08:00
|
|
|
col = string(rune((num-1)%26+65)) + col
|
Huge refactorig for consistent col/row numbering (#356)
* Huge refactorig for consistent col/row numbering
Started from simply changing ToALphaString()/TitleToNumber() logic and related fixes.
But have to go deeper, do fixes, after do related fixes and again and again.
Major improvements:
1. Tests made stronger again (But still be weak).
2. "Empty" returns for incorrect input replaces with panic.
3. Check for correct col/row/cell naming & addressing by default.
4. Removed huge amount of duplicated code.
5. Removed ToALphaString(), TitleToNumber() and it helpers functions at all,
and replaced with SplitCellName(), JoinCellName(), ColumnNameToNumber(), ColumnNumberToName(), CellNameToCoordinates(), CoordinatesToCellName().
6. Minor fixes for internal variable naming for code readability (ex. col, row for input params, colIdx, rowIdx for slice indexes etc).
* Formatting fixes
2019-03-20 00:14:41 +08:00
|
|
|
num = (num - 1) / 26
|
|
|
|
}
|
|
|
|
return col, nil
|
2016-08-30 11:51:31 +08:00
|
|
|
}
|
2017-08-19 13:37:15 +08:00
|
|
|
|
2019-04-20 14:57:50 +08:00
|
|
|
// CellNameToCoordinates converts alphanumeric cell name to [X, Y] coordinates
|
|
|
|
// or returns an error.
|
Huge refactorig for consistent col/row numbering (#356)
* Huge refactorig for consistent col/row numbering
Started from simply changing ToALphaString()/TitleToNumber() logic and related fixes.
But have to go deeper, do fixes, after do related fixes and again and again.
Major improvements:
1. Tests made stronger again (But still be weak).
2. "Empty" returns for incorrect input replaces with panic.
3. Check for correct col/row/cell naming & addressing by default.
4. Removed huge amount of duplicated code.
5. Removed ToALphaString(), TitleToNumber() and it helpers functions at all,
and replaced with SplitCellName(), JoinCellName(), ColumnNameToNumber(), ColumnNumberToName(), CellNameToCoordinates(), CoordinatesToCellName().
6. Minor fixes for internal variable naming for code readability (ex. col, row for input params, colIdx, rowIdx for slice indexes etc).
* Formatting fixes
2019-03-20 00:14:41 +08:00
|
|
|
//
|
|
|
|
// Example:
|
2019-03-23 20:08:06 +08:00
|
|
|
//
|
2022-08-13 11:21:59 +08:00
|
|
|
// excelize.CellNameToCoordinates("A1") // returns 1, 1, nil
|
|
|
|
// excelize.CellNameToCoordinates("Z3") // returns 26, 3, nil
|
Huge refactorig for consistent col/row numbering (#356)
* Huge refactorig for consistent col/row numbering
Started from simply changing ToALphaString()/TitleToNumber() logic and related fixes.
But have to go deeper, do fixes, after do related fixes and again and again.
Major improvements:
1. Tests made stronger again (But still be weak).
2. "Empty" returns for incorrect input replaces with panic.
3. Check for correct col/row/cell naming & addressing by default.
4. Removed huge amount of duplicated code.
5. Removed ToALphaString(), TitleToNumber() and it helpers functions at all,
and replaced with SplitCellName(), JoinCellName(), ColumnNameToNumber(), ColumnNumberToName(), CellNameToCoordinates(), CoordinatesToCellName().
6. Minor fixes for internal variable naming for code readability (ex. col, row for input params, colIdx, rowIdx for slice indexes etc).
* Formatting fixes
2019-03-20 00:14:41 +08:00
|
|
|
func CellNameToCoordinates(cell string) (int, int, error) {
|
2022-04-04 00:21:33 +08:00
|
|
|
colName, row, err := SplitCellName(cell)
|
Huge refactorig for consistent col/row numbering (#356)
* Huge refactorig for consistent col/row numbering
Started from simply changing ToALphaString()/TitleToNumber() logic and related fixes.
But have to go deeper, do fixes, after do related fixes and again and again.
Major improvements:
1. Tests made stronger again (But still be weak).
2. "Empty" returns for incorrect input replaces with panic.
3. Check for correct col/row/cell naming & addressing by default.
4. Removed huge amount of duplicated code.
5. Removed ToALphaString(), TitleToNumber() and it helpers functions at all,
and replaced with SplitCellName(), JoinCellName(), ColumnNameToNumber(), ColumnNumberToName(), CellNameToCoordinates(), CoordinatesToCellName().
6. Minor fixes for internal variable naming for code readability (ex. col, row for input params, colIdx, rowIdx for slice indexes etc).
* Formatting fixes
2019-03-20 00:14:41 +08:00
|
|
|
if err != nil {
|
2021-12-07 00:26:53 +08:00
|
|
|
return -1, -1, newCellNameToCoordinatesError(cell, err)
|
2017-11-05 09:16:41 +08:00
|
|
|
}
|
2020-05-29 00:26:40 +08:00
|
|
|
if row > TotalRows {
|
2021-08-17 00:01:44 +08:00
|
|
|
return -1, -1, ErrMaxRows
|
2020-05-29 00:26:40 +08:00
|
|
|
}
|
2022-04-04 00:21:33 +08:00
|
|
|
col, err := ColumnNameToNumber(colName)
|
2020-05-23 13:29:51 +08:00
|
|
|
return col, row, err
|
2017-11-05 09:16:41 +08:00
|
|
|
}
|
2018-01-19 17:32:54 +08:00
|
|
|
|
2019-03-23 20:08:06 +08:00
|
|
|
// CoordinatesToCellName converts [X, Y] coordinates to alpha-numeric cell
|
|
|
|
// name or returns an error.
|
2018-01-19 17:32:54 +08:00
|
|
|
//
|
Huge refactorig for consistent col/row numbering (#356)
* Huge refactorig for consistent col/row numbering
Started from simply changing ToALphaString()/TitleToNumber() logic and related fixes.
But have to go deeper, do fixes, after do related fixes and again and again.
Major improvements:
1. Tests made stronger again (But still be weak).
2. "Empty" returns for incorrect input replaces with panic.
3. Check for correct col/row/cell naming & addressing by default.
4. Removed huge amount of duplicated code.
5. Removed ToALphaString(), TitleToNumber() and it helpers functions at all,
and replaced with SplitCellName(), JoinCellName(), ColumnNameToNumber(), ColumnNumberToName(), CellNameToCoordinates(), CoordinatesToCellName().
6. Minor fixes for internal variable naming for code readability (ex. col, row for input params, colIdx, rowIdx for slice indexes etc).
* Formatting fixes
2019-03-20 00:14:41 +08:00
|
|
|
// Example:
|
2018-01-19 17:32:54 +08:00
|
|
|
//
|
2022-08-13 11:21:59 +08:00
|
|
|
// excelize.CoordinatesToCellName(1, 1) // returns "A1", nil
|
|
|
|
// excelize.CoordinatesToCellName(1, 1, true) // returns "$A$1", nil
|
2021-02-02 22:23:16 +08:00
|
|
|
func CoordinatesToCellName(col, row int, abs ...bool) (string, error) {
|
Huge refactorig for consistent col/row numbering (#356)
* Huge refactorig for consistent col/row numbering
Started from simply changing ToALphaString()/TitleToNumber() logic and related fixes.
But have to go deeper, do fixes, after do related fixes and again and again.
Major improvements:
1. Tests made stronger again (But still be weak).
2. "Empty" returns for incorrect input replaces with panic.
3. Check for correct col/row/cell naming & addressing by default.
4. Removed huge amount of duplicated code.
5. Removed ToALphaString(), TitleToNumber() and it helpers functions at all,
and replaced with SplitCellName(), JoinCellName(), ColumnNameToNumber(), ColumnNumberToName(), CellNameToCoordinates(), CoordinatesToCellName().
6. Minor fixes for internal variable naming for code readability (ex. col, row for input params, colIdx, rowIdx for slice indexes etc).
* Formatting fixes
2019-03-20 00:14:41 +08:00
|
|
|
if col < 1 || row < 1 {
|
2023-09-28 08:53:54 +08:00
|
|
|
return "", newCoordinatesToCellNameError(col, row)
|
Huge refactorig for consistent col/row numbering (#356)
* Huge refactorig for consistent col/row numbering
Started from simply changing ToALphaString()/TitleToNumber() logic and related fixes.
But have to go deeper, do fixes, after do related fixes and again and again.
Major improvements:
1. Tests made stronger again (But still be weak).
2. "Empty" returns for incorrect input replaces with panic.
3. Check for correct col/row/cell naming & addressing by default.
4. Removed huge amount of duplicated code.
5. Removed ToALphaString(), TitleToNumber() and it helpers functions at all,
and replaced with SplitCellName(), JoinCellName(), ColumnNameToNumber(), ColumnNumberToName(), CellNameToCoordinates(), CoordinatesToCellName().
6. Minor fixes for internal variable naming for code readability (ex. col, row for input params, colIdx, rowIdx for slice indexes etc).
* Formatting fixes
2019-03-20 00:14:41 +08:00
|
|
|
}
|
2021-02-02 22:23:16 +08:00
|
|
|
sign := ""
|
|
|
|
for _, a := range abs {
|
|
|
|
if a {
|
|
|
|
sign = "$"
|
|
|
|
}
|
|
|
|
}
|
2022-04-04 00:21:33 +08:00
|
|
|
colName, err := ColumnNumberToName(col)
|
|
|
|
return sign + colName + sign + strconv.Itoa(row), err
|
Huge refactorig for consistent col/row numbering (#356)
* Huge refactorig for consistent col/row numbering
Started from simply changing ToALphaString()/TitleToNumber() logic and related fixes.
But have to go deeper, do fixes, after do related fixes and again and again.
Major improvements:
1. Tests made stronger again (But still be weak).
2. "Empty" returns for incorrect input replaces with panic.
3. Check for correct col/row/cell naming & addressing by default.
4. Removed huge amount of duplicated code.
5. Removed ToALphaString(), TitleToNumber() and it helpers functions at all,
and replaced with SplitCellName(), JoinCellName(), ColumnNameToNumber(), ColumnNumberToName(), CellNameToCoordinates(), CoordinatesToCellName().
6. Minor fixes for internal variable naming for code readability (ex. col, row for input params, colIdx, rowIdx for slice indexes etc).
* Formatting fixes
2019-03-20 00:14:41 +08:00
|
|
|
}
|
2018-01-19 17:32:54 +08:00
|
|
|
|
2022-09-28 00:04:17 +08:00
|
|
|
// rangeRefToCoordinates provides a function to convert range reference to a
|
2021-08-06 22:44:43 +08:00
|
|
|
// pair of coordinates.
|
2022-09-28 00:04:17 +08:00
|
|
|
func rangeRefToCoordinates(ref string) ([]int, error) {
|
2022-06-12 00:19:12 +08:00
|
|
|
rng := strings.Split(strings.ReplaceAll(ref, "$", ""), ":")
|
2021-08-06 22:44:43 +08:00
|
|
|
if len(rng) < 2 {
|
|
|
|
return nil, ErrParameterInvalid
|
|
|
|
}
|
2022-09-28 00:04:17 +08:00
|
|
|
return cellRefsToCoordinates(rng[0], rng[1])
|
2021-08-06 22:44:43 +08:00
|
|
|
}
|
|
|
|
|
2022-09-28 00:04:17 +08:00
|
|
|
// cellRefsToCoordinates provides a function to convert cell range to a
|
2021-08-06 22:44:43 +08:00
|
|
|
// pair of coordinates.
|
2022-09-28 00:04:17 +08:00
|
|
|
func cellRefsToCoordinates(firstCell, lastCell string) ([]int, error) {
|
2021-08-06 22:44:43 +08:00
|
|
|
coordinates := make([]int, 4)
|
|
|
|
var err error
|
|
|
|
coordinates[0], coordinates[1], err = CellNameToCoordinates(firstCell)
|
|
|
|
if err != nil {
|
|
|
|
return coordinates, err
|
|
|
|
}
|
|
|
|
coordinates[2], coordinates[3], err = CellNameToCoordinates(lastCell)
|
|
|
|
return coordinates, err
|
|
|
|
}
|
|
|
|
|
2022-09-18 00:07:15 +08:00
|
|
|
// sortCoordinates provides a function to correct the cell range, such
|
2021-08-06 22:44:43 +08:00
|
|
|
// correct C1:B3 to B1:C3.
|
|
|
|
func sortCoordinates(coordinates []int) error {
|
|
|
|
if len(coordinates) != 4 {
|
|
|
|
return ErrCoordinates
|
|
|
|
}
|
|
|
|
if coordinates[2] < coordinates[0] {
|
|
|
|
coordinates[2], coordinates[0] = coordinates[0], coordinates[2]
|
|
|
|
}
|
|
|
|
if coordinates[3] < coordinates[1] {
|
|
|
|
coordinates[3], coordinates[1] = coordinates[1], coordinates[3]
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-09-28 00:04:17 +08:00
|
|
|
// coordinatesToRangeRef provides a function to convert a pair of coordinates
|
|
|
|
// to range reference.
|
Breaking change: changed the function signature for 11 exported functions
* Change
`func (f *File) NewConditionalStyle(style string) (int, error)`
to
`func (f *File) NewConditionalStyle(style *Style) (int, error)`
* Change
`func (f *File) NewStyle(style interface{}) (int, error)`
to
`func (f *File) NewStyle(style *Style) (int, error)`
* Change
`func (f *File) AddChart(sheet, cell, opts string, combo ...string) error`
to
`func (f *File) AddChart(sheet, cell string, chart *ChartOptions, combo ...*ChartOptions) error`
* Change
`func (f *File) AddChartSheet(sheet, opts string, combo ...string) error`
to
`func (f *File) AddChartSheet(sheet string, chart *ChartOptions, combo ...*ChartOptions) error`
* Change
`func (f *File) AddShape(sheet, cell, opts string) error`
to
`func (f *File) AddShape(sheet, cell string, opts *Shape) error`
* Change
`func (f *File) AddPictureFromBytes(sheet, cell, opts, name, extension string, file []byte) error`
to
`func (f *File) AddPictureFromBytes(sheet, cell, name, extension string, file []byte, opts *PictureOptions) error`
* Change
`func (f *File) AddTable(sheet, hCell, vCell, opts string) error`
to
`func (f *File) AddTable(sheet, reference string, opts *TableOptions) error`
* Change
`func (sw *StreamWriter) AddTable(hCell, vCell, opts string) error`
to
`func (sw *StreamWriter) AddTable(reference string, opts *TableOptions) error`
* Change
`func (f *File) AutoFilter(sheet, hCell, vCell, opts string) error`
to
`func (f *File) AutoFilter(sheet, reference string, opts *AutoFilterOptions) error`
* Change
`func (f *File) SetPanes(sheet, panes string) error`
to
`func (f *File) SetPanes(sheet string, panes *Panes) error`
* Change
`func (sw *StreamWriter) AddTable(hCell, vCell, opts string) error`
to
`func (sw *StreamWriter) AddTable(reference string, opts *TableOptions) error`
* Change
`func (f *File) SetConditionalFormat(sheet, reference, opts string) error`
to
`func (f *File) SetConditionalFormat(sheet, reference string, opts []ConditionalFormatOptions) error`
* Add exported types:
* AutoFilterListOptions
* AutoFilterOptions
* Chart
* ChartAxis
* ChartDimension
* ChartLegend
* ChartLine
* ChartMarker
* ChartPlotArea
* ChartSeries
* ChartTitle
* ConditionalFormatOptions
* PaneOptions
* Panes
* PictureOptions
* Shape
* ShapeColor
* ShapeLine
* ShapeParagraph
* TableOptions
* This added support for set sheet visible as very hidden
* Return error when missing required parameters for set defined name
* Update unit test and comments
2022-12-30 00:50:08 +08:00
|
|
|
func (f *File) coordinatesToRangeRef(coordinates []int, abs ...bool) (string, error) {
|
2021-08-06 22:44:43 +08:00
|
|
|
if len(coordinates) != 4 {
|
|
|
|
return "", ErrCoordinates
|
|
|
|
}
|
Breaking change: changed the function signature for 11 exported functions
* Change
`func (f *File) NewConditionalStyle(style string) (int, error)`
to
`func (f *File) NewConditionalStyle(style *Style) (int, error)`
* Change
`func (f *File) NewStyle(style interface{}) (int, error)`
to
`func (f *File) NewStyle(style *Style) (int, error)`
* Change
`func (f *File) AddChart(sheet, cell, opts string, combo ...string) error`
to
`func (f *File) AddChart(sheet, cell string, chart *ChartOptions, combo ...*ChartOptions) error`
* Change
`func (f *File) AddChartSheet(sheet, opts string, combo ...string) error`
to
`func (f *File) AddChartSheet(sheet string, chart *ChartOptions, combo ...*ChartOptions) error`
* Change
`func (f *File) AddShape(sheet, cell, opts string) error`
to
`func (f *File) AddShape(sheet, cell string, opts *Shape) error`
* Change
`func (f *File) AddPictureFromBytes(sheet, cell, opts, name, extension string, file []byte) error`
to
`func (f *File) AddPictureFromBytes(sheet, cell, name, extension string, file []byte, opts *PictureOptions) error`
* Change
`func (f *File) AddTable(sheet, hCell, vCell, opts string) error`
to
`func (f *File) AddTable(sheet, reference string, opts *TableOptions) error`
* Change
`func (sw *StreamWriter) AddTable(hCell, vCell, opts string) error`
to
`func (sw *StreamWriter) AddTable(reference string, opts *TableOptions) error`
* Change
`func (f *File) AutoFilter(sheet, hCell, vCell, opts string) error`
to
`func (f *File) AutoFilter(sheet, reference string, opts *AutoFilterOptions) error`
* Change
`func (f *File) SetPanes(sheet, panes string) error`
to
`func (f *File) SetPanes(sheet string, panes *Panes) error`
* Change
`func (sw *StreamWriter) AddTable(hCell, vCell, opts string) error`
to
`func (sw *StreamWriter) AddTable(reference string, opts *TableOptions) error`
* Change
`func (f *File) SetConditionalFormat(sheet, reference, opts string) error`
to
`func (f *File) SetConditionalFormat(sheet, reference string, opts []ConditionalFormatOptions) error`
* Add exported types:
* AutoFilterListOptions
* AutoFilterOptions
* Chart
* ChartAxis
* ChartDimension
* ChartLegend
* ChartLine
* ChartMarker
* ChartPlotArea
* ChartSeries
* ChartTitle
* ConditionalFormatOptions
* PaneOptions
* Panes
* PictureOptions
* Shape
* ShapeColor
* ShapeLine
* ShapeParagraph
* TableOptions
* This added support for set sheet visible as very hidden
* Return error when missing required parameters for set defined name
* Update unit test and comments
2022-12-30 00:50:08 +08:00
|
|
|
firstCell, err := CoordinatesToCellName(coordinates[0], coordinates[1], abs...)
|
2021-08-06 22:44:43 +08:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
Breaking change: changed the function signature for 11 exported functions
* Change
`func (f *File) NewConditionalStyle(style string) (int, error)`
to
`func (f *File) NewConditionalStyle(style *Style) (int, error)`
* Change
`func (f *File) NewStyle(style interface{}) (int, error)`
to
`func (f *File) NewStyle(style *Style) (int, error)`
* Change
`func (f *File) AddChart(sheet, cell, opts string, combo ...string) error`
to
`func (f *File) AddChart(sheet, cell string, chart *ChartOptions, combo ...*ChartOptions) error`
* Change
`func (f *File) AddChartSheet(sheet, opts string, combo ...string) error`
to
`func (f *File) AddChartSheet(sheet string, chart *ChartOptions, combo ...*ChartOptions) error`
* Change
`func (f *File) AddShape(sheet, cell, opts string) error`
to
`func (f *File) AddShape(sheet, cell string, opts *Shape) error`
* Change
`func (f *File) AddPictureFromBytes(sheet, cell, opts, name, extension string, file []byte) error`
to
`func (f *File) AddPictureFromBytes(sheet, cell, name, extension string, file []byte, opts *PictureOptions) error`
* Change
`func (f *File) AddTable(sheet, hCell, vCell, opts string) error`
to
`func (f *File) AddTable(sheet, reference string, opts *TableOptions) error`
* Change
`func (sw *StreamWriter) AddTable(hCell, vCell, opts string) error`
to
`func (sw *StreamWriter) AddTable(reference string, opts *TableOptions) error`
* Change
`func (f *File) AutoFilter(sheet, hCell, vCell, opts string) error`
to
`func (f *File) AutoFilter(sheet, reference string, opts *AutoFilterOptions) error`
* Change
`func (f *File) SetPanes(sheet, panes string) error`
to
`func (f *File) SetPanes(sheet string, panes *Panes) error`
* Change
`func (sw *StreamWriter) AddTable(hCell, vCell, opts string) error`
to
`func (sw *StreamWriter) AddTable(reference string, opts *TableOptions) error`
* Change
`func (f *File) SetConditionalFormat(sheet, reference, opts string) error`
to
`func (f *File) SetConditionalFormat(sheet, reference string, opts []ConditionalFormatOptions) error`
* Add exported types:
* AutoFilterListOptions
* AutoFilterOptions
* Chart
* ChartAxis
* ChartDimension
* ChartLegend
* ChartLine
* ChartMarker
* ChartPlotArea
* ChartSeries
* ChartTitle
* ConditionalFormatOptions
* PaneOptions
* Panes
* PictureOptions
* Shape
* ShapeColor
* ShapeLine
* ShapeParagraph
* TableOptions
* This added support for set sheet visible as very hidden
* Return error when missing required parameters for set defined name
* Update unit test and comments
2022-12-30 00:50:08 +08:00
|
|
|
lastCell, err := CoordinatesToCellName(coordinates[2], coordinates[3], abs...)
|
2021-08-06 22:44:43 +08:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
return firstCell + ":" + lastCell, err
|
|
|
|
}
|
|
|
|
|
2022-04-04 00:21:33 +08:00
|
|
|
// getDefinedNameRefTo convert defined name to reference range.
|
2023-09-16 12:21:11 +08:00
|
|
|
func (f *File) getDefinedNameRefTo(definedNameName, currentSheet string) (refTo string) {
|
2022-04-04 00:21:33 +08:00
|
|
|
var workbookRefTo, worksheetRefTo string
|
|
|
|
for _, definedName := range f.GetDefinedName() {
|
|
|
|
if definedName.Name == definedNameName {
|
|
|
|
// worksheet scope takes precedence over scope workbook when both definedNames exist
|
|
|
|
if definedName.Scope == "Workbook" {
|
|
|
|
workbookRefTo = definedName.RefersTo
|
|
|
|
}
|
|
|
|
if definedName.Scope == currentSheet {
|
|
|
|
worksheetRefTo = definedName.RefersTo
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
refTo = workbookRefTo
|
|
|
|
if worksheetRefTo != "" {
|
|
|
|
refTo = worksheetRefTo
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-09-18 00:07:15 +08:00
|
|
|
// flatSqref convert reference sequence to cell reference list.
|
2021-08-06 22:44:43 +08:00
|
|
|
func (f *File) flatSqref(sqref string) (cells map[int][][]int, err error) {
|
|
|
|
var coordinates []int
|
|
|
|
cells = make(map[int][][]int)
|
|
|
|
for _, ref := range strings.Fields(sqref) {
|
|
|
|
rng := strings.Split(ref, ":")
|
|
|
|
switch len(rng) {
|
|
|
|
case 1:
|
|
|
|
var col, row int
|
|
|
|
col, row, err = CellNameToCoordinates(rng[0])
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
cells[col] = append(cells[col], []int{col, row})
|
|
|
|
case 2:
|
2022-09-28 00:04:17 +08:00
|
|
|
if coordinates, err = rangeRefToCoordinates(ref); err != nil {
|
2021-08-06 22:44:43 +08:00
|
|
|
return
|
|
|
|
}
|
|
|
|
_ = sortCoordinates(coordinates)
|
|
|
|
for c := coordinates[0]; c <= coordinates[2]; c++ {
|
|
|
|
for r := coordinates[1]; r <= coordinates[3]; r++ {
|
|
|
|
cells[c] = append(cells[c], []int{c, r})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-04-04 00:21:33 +08:00
|
|
|
// inCoordinates provides a method to check if a coordinate is present in
|
2021-08-06 22:44:43 +08:00
|
|
|
// coordinates array, and return the index of its location, otherwise
|
|
|
|
// return -1.
|
|
|
|
func inCoordinates(a [][]int, x []int) int {
|
|
|
|
for idx, n := range a {
|
|
|
|
if x[0] == n[0] && x[1] == n[1] {
|
|
|
|
return idx
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return -1
|
|
|
|
}
|
|
|
|
|
|
|
|
// inStrSlice provides a method to check if an element is present in an array,
|
|
|
|
// and return the index of its location, otherwise return -1.
|
2022-02-13 00:06:30 +08:00
|
|
|
func inStrSlice(a []string, x string, caseSensitive bool) int {
|
2021-08-06 22:44:43 +08:00
|
|
|
for idx, n := range a {
|
2022-02-13 00:06:30 +08:00
|
|
|
if !caseSensitive && strings.EqualFold(x, n) {
|
|
|
|
return idx
|
|
|
|
}
|
2021-08-06 22:44:43 +08:00
|
|
|
if x == n {
|
|
|
|
return idx
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return -1
|
|
|
|
}
|
|
|
|
|
2022-04-04 00:21:33 +08:00
|
|
|
// inFloat64Slice provides a method to check if an element is present in a
|
2021-11-09 00:10:09 +08:00
|
|
|
// float64 array, and return the index of its location, otherwise return -1.
|
|
|
|
func inFloat64Slice(a []float64, x float64) int {
|
|
|
|
for idx, n := range a {
|
|
|
|
if x == n {
|
|
|
|
return idx
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return -1
|
|
|
|
}
|
|
|
|
|
Huge refactorig for consistent col/row numbering (#356)
* Huge refactorig for consistent col/row numbering
Started from simply changing ToALphaString()/TitleToNumber() logic and related fixes.
But have to go deeper, do fixes, after do related fixes and again and again.
Major improvements:
1. Tests made stronger again (But still be weak).
2. "Empty" returns for incorrect input replaces with panic.
3. Check for correct col/row/cell naming & addressing by default.
4. Removed huge amount of duplicated code.
5. Removed ToALphaString(), TitleToNumber() and it helpers functions at all,
and replaced with SplitCellName(), JoinCellName(), ColumnNameToNumber(), ColumnNumberToName(), CellNameToCoordinates(), CoordinatesToCellName().
6. Minor fixes for internal variable naming for code readability (ex. col, row for input params, colIdx, rowIdx for slice indexes etc).
* Formatting fixes
2019-03-20 00:14:41 +08:00
|
|
|
// boolPtr returns a pointer to a bool with the given value.
|
|
|
|
func boolPtr(b bool) *bool { return &b }
|
2018-01-19 17:32:54 +08:00
|
|
|
|
2022-04-04 00:21:33 +08:00
|
|
|
// intPtr returns a pointer to an int with the given value.
|
2019-12-23 00:07:40 +08:00
|
|
|
func intPtr(i int) *int { return &i }
|
|
|
|
|
This closes #1358, made a refactor with breaking changes, see details:
This made a refactor with breaking changes:
Motivation and Context
When I decided to add set horizontal centered support for this library to resolve #1358, the reason I made this huge breaking change was:
- There are too many exported types for set sheet view, properties, and format properties, although a function using the functional options pattern can be optimized by returning an anonymous function, these types or property set or get function has no binding categorization, so I change these functions like `SetAppProps` to accept a pointer of options structure.
- Users can not easily find out which properties should be in the `SetSheetPrOptions` or `SetSheetFormatPr` categories
- Nested properties cannot proceed modify easily
Introduce 5 new export data types:
`HeaderFooterOptions`, `PageLayoutMarginsOptions`, `PageLayoutOptions`, `SheetPropsOptions`, and `ViewOptions`
Rename 4 exported data types:
- Rename `PivotTableOption` to `PivotTableOptions`
- Rename `FormatHeaderFooter` to `HeaderFooterOptions`
- Rename `FormatSheetProtection` to `SheetProtectionOptions`
- Rename `SparklineOption` to `SparklineOptions`
Remove 54 exported types:
`AutoPageBreaks`, `BaseColWidth`, `BlackAndWhite`, `CodeName`, `CustomHeight`, `Date1904`, `DefaultColWidth`, `DefaultGridColor`, `DefaultRowHeight`, `EnableFormatConditionsCalculation`, `FilterPrivacy`, `FirstPageNumber`, `FitToHeight`, `FitToPage`, `FitToWidth`, `OutlineSummaryBelow`, `PageLayoutOption`, `PageLayoutOptionPtr`, `PageLayoutOrientation`, `PageLayoutPaperSize`, `PageLayoutScale`, `PageMarginBottom`, `PageMarginFooter`, `PageMarginHeader`, `PageMarginLeft`, `PageMarginRight`, `PageMarginsOptions`, `PageMarginsOptionsPtr`, `PageMarginTop`, `Published`, `RightToLeft`, `SheetFormatPrOptions`, `SheetFormatPrOptionsPtr`, `SheetPrOption`, `SheetPrOptionPtr`, `SheetViewOption`, `SheetViewOptionPtr`, `ShowFormulas`, `ShowGridLines`, `ShowRowColHeaders`, `ShowRuler`, `ShowZeros`, `TabColorIndexed`, `TabColorRGB`, `TabColorTheme`, `TabColorTint`, `ThickBottom`, `ThickTop`, `TopLeftCell`, `View`, `WorkbookPrOption`, `WorkbookPrOptionPtr`, `ZeroHeight` and `ZoomScale`
Remove 2 exported constants:
`OrientationPortrait` and `OrientationLandscape`
Change 8 functions:
- Change the `func (f *File) SetPageLayout(sheet string, opts ...PageLayoutOption) error` to `func (f *File) SetPageLayout(sheet string, opts *PageLayoutOptions) error`
- Change the `func (f *File) GetPageLayout(sheet string, opts ...PageLayoutOptionPtr) error` to `func (f *File) GetPageLayout(sheet string) (PageLayoutOptions, error)`
- Change the `func (f *File) SetPageMargins(sheet string, opts ...PageMarginsOptions) error` to `func (f *File) SetPageMargins(sheet string, opts *PageLayoutMarginsOptions) error`
- Change the `func (f *File) GetPageMargins(sheet string, opts ...PageMarginsOptionsPtr) error` to `func (f *File) GetPageMargins(sheet string) (PageLayoutMarginsOptions, error)`
- Change the `func (f *File) SetSheetViewOptions(sheet string, viewIndex int, opts ...SheetViewOption) error` to `func (f *File) SetSheetView(sheet string, viewIndex int, opts *ViewOptions) error`
- Change the `func (f *File) GetSheetViewOptions(sheet string, viewIndex int, opts ...SheetViewOptionPtr) error` to `func (f *File) GetSheetView(sheet string, viewIndex int) (ViewOptions, error)`
- Change the `func (f *File) SetWorkbookPrOptions(opts ...WorkbookPrOption) error` to `func (f *File) SetWorkbookProps(opts *WorkbookPropsOptions) error`
- Change the `func (f *File) GetWorkbookPrOptions(opts ...WorkbookPrOptionPtr) error` to `func (f *File) GetWorkbookProps() (WorkbookPropsOptions, error)`
Introduce new function to instead of existing functions:
- New function `func (f *File) SetSheetProps(sheet string, opts *SheetPropsOptions) error` instead of `func (f *File) SetSheetPrOptions(sheet string, opts ...SheetPrOption) error` and `func (f *File) SetSheetFormatPr(sheet string, opts ...SheetFormatPrOption
2022-09-29 22:00:21 +08:00
|
|
|
// uintPtr returns a pointer to an int with the given value.
|
|
|
|
func uintPtr(i uint) *uint { return &i }
|
|
|
|
|
2021-11-13 14:11:16 +08:00
|
|
|
// float64Ptr returns a pointer to a float64 with the given value.
|
2019-12-23 00:07:40 +08:00
|
|
|
func float64Ptr(f float64) *float64 { return &f }
|
|
|
|
|
|
|
|
// stringPtr returns a pointer to a string with the given value.
|
|
|
|
func stringPtr(s string) *string { return &s }
|
|
|
|
|
2023-08-24 23:51:07 +08:00
|
|
|
// Value extracts string data type text from a attribute value.
|
2023-09-16 12:21:11 +08:00
|
|
|
func (avb *attrValString) Value() string {
|
|
|
|
if avb != nil && avb.Val != nil {
|
|
|
|
return *avb.Val
|
2023-08-24 23:51:07 +08:00
|
|
|
}
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
|
|
|
|
// Value extracts boolean data type value from a attribute value.
|
2023-09-16 12:21:11 +08:00
|
|
|
func (avb *attrValBool) Value() bool {
|
|
|
|
if avb != nil && avb.Val != nil {
|
|
|
|
return *avb.Val
|
2023-08-24 23:51:07 +08:00
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
// Value extracts float64 data type numeric from a attribute value.
|
|
|
|
func (attr *attrValFloat) Value() float64 {
|
|
|
|
if attr != nil && attr.Val != nil {
|
|
|
|
return *attr.Val
|
|
|
|
}
|
|
|
|
return 0
|
|
|
|
}
|
|
|
|
|
2021-11-14 00:17:31 +08:00
|
|
|
// MarshalXML convert the boolean data type to literal values 0 or 1 on
|
|
|
|
// serialization.
|
2021-11-13 14:11:16 +08:00
|
|
|
func (avb attrValBool) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
|
|
|
|
attr := xml.Attr{
|
|
|
|
Name: xml.Name{
|
|
|
|
Space: start.Name.Space,
|
|
|
|
Local: "val",
|
|
|
|
},
|
|
|
|
Value: "0",
|
|
|
|
}
|
|
|
|
if avb.Val != nil {
|
|
|
|
if *avb.Val {
|
|
|
|
attr.Value = "1"
|
|
|
|
} else {
|
|
|
|
attr.Value = "0"
|
|
|
|
}
|
|
|
|
}
|
|
|
|
start.Attr = []xml.Attr{attr}
|
2022-03-24 00:19:30 +08:00
|
|
|
if err := e.EncodeToken(start); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return e.EncodeToken(start.End())
|
2021-11-13 14:11:16 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// UnmarshalXML convert the literal values true, false, 1, 0 of the XML
|
2021-11-14 00:17:31 +08:00
|
|
|
// attribute to boolean data type on deserialization.
|
2021-11-13 14:11:16 +08:00
|
|
|
func (avb *attrValBool) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
|
|
|
|
for {
|
|
|
|
t, err := d.Token()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
found := false
|
|
|
|
switch t.(type) {
|
|
|
|
case xml.StartElement:
|
2021-12-07 00:26:53 +08:00
|
|
|
return ErrAttrValBool
|
2021-11-13 14:11:16 +08:00
|
|
|
case xml.EndElement:
|
|
|
|
found = true
|
|
|
|
}
|
|
|
|
if found {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
for _, attr := range start.Attr {
|
|
|
|
if attr.Name.Local == "val" {
|
|
|
|
if attr.Value == "" {
|
|
|
|
val := true
|
|
|
|
avb.Val = &val
|
|
|
|
} else {
|
|
|
|
val, err := strconv.ParseBool(attr.Value)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
avb.Val = &val
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
2022-01-15 00:06:34 +08:00
|
|
|
defaultVal := true
|
|
|
|
avb.Val = &defaultVal
|
2021-11-13 14:11:16 +08:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-09-16 12:21:11 +08:00
|
|
|
// MarshalXML encodes ext element with specified namespace attributes on
|
|
|
|
// serialization.
|
|
|
|
func (ext xlsxExt) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
|
|
|
|
start.Attr = ext.xmlns
|
|
|
|
return e.EncodeElement(decodeExt{URI: ext.URI, Content: ext.Content}, start)
|
|
|
|
}
|
|
|
|
|
|
|
|
// UnmarshalXML extracts ext element attributes namespace by giving XML decoder
|
|
|
|
// on deserialization.
|
|
|
|
func (ext *xlsxExt) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
|
|
|
|
for _, attr := range start.Attr {
|
|
|
|
if attr.Name.Local == "uri" {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
if attr.Name.Space == "xmlns" {
|
|
|
|
attr.Name.Space = ""
|
|
|
|
attr.Name.Local = "xmlns:" + attr.Name.Local
|
|
|
|
}
|
|
|
|
ext.xmlns = append(ext.xmlns, attr)
|
|
|
|
}
|
|
|
|
e := &decodeExt{}
|
|
|
|
if err := d.DecodeElement(&e, &start); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
ext.URI, ext.Content = e.URI, e.Content
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2018-10-17 00:28:31 +08:00
|
|
|
// namespaceStrictToTransitional provides a method to convert Strict and
|
|
|
|
// Transitional namespaces.
|
|
|
|
func namespaceStrictToTransitional(content []byte) []byte {
|
2022-01-23 00:32:34 +08:00
|
|
|
namespaceTranslationDic := map[string]string{
|
2023-01-13 00:05:46 +08:00
|
|
|
StrictNameSpaceDocumentPropertiesVariantTypes: NameSpaceDocumentPropertiesVariantTypes.Value,
|
|
|
|
StrictNameSpaceDrawingMLMain: NameSpaceDrawingMLMain,
|
|
|
|
StrictNameSpaceExtendedProperties: NameSpaceExtendedProperties,
|
|
|
|
StrictNameSpaceSpreadSheet: NameSpaceSpreadSheet.Value,
|
|
|
|
StrictSourceRelationship: SourceRelationship.Value,
|
|
|
|
StrictSourceRelationshipChart: SourceRelationshipChart,
|
|
|
|
StrictSourceRelationshipComments: SourceRelationshipComments,
|
|
|
|
StrictSourceRelationshipExtendProperties: SourceRelationshipExtendProperties,
|
|
|
|
StrictSourceRelationshipImage: SourceRelationshipImage,
|
|
|
|
StrictSourceRelationshipOfficeDocument: SourceRelationshipOfficeDocument,
|
2018-10-17 00:28:31 +08:00
|
|
|
}
|
|
|
|
for s, n := range namespaceTranslationDic {
|
2020-08-06 13:58:40 +08:00
|
|
|
content = bytesReplace(content, []byte(s), []byte(n), -1)
|
2018-10-17 00:28:31 +08:00
|
|
|
}
|
|
|
|
return content
|
|
|
|
}
|
2018-11-02 23:08:31 +08:00
|
|
|
|
2022-09-18 00:07:15 +08:00
|
|
|
// bytesReplace replace source bytes with given target.
|
|
|
|
func bytesReplace(s, source, target []byte, n int) []byte {
|
2020-04-02 00:41:14 +08:00
|
|
|
if n == 0 {
|
|
|
|
return s
|
|
|
|
}
|
|
|
|
|
2022-09-18 00:07:15 +08:00
|
|
|
if len(source) < len(target) {
|
|
|
|
return bytes.Replace(s, source, target, n)
|
2020-04-02 00:41:14 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
if n < 0 {
|
|
|
|
n = len(s)
|
|
|
|
}
|
|
|
|
|
|
|
|
var wid, i, j, w int
|
|
|
|
for i, j = 0, 0; i < len(s) && j < n; j++ {
|
2022-09-18 00:07:15 +08:00
|
|
|
wid = bytes.Index(s[i:], source)
|
2020-04-02 00:41:14 +08:00
|
|
|
if wid < 0 {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
|
|
|
|
w += copy(s[w:], s[i:i+wid])
|
2022-09-18 00:07:15 +08:00
|
|
|
w += copy(s[w:], target)
|
|
|
|
i += wid + len(source)
|
2020-04-02 00:41:14 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
w += copy(s[w:], s[i:])
|
2021-11-17 00:25:36 +08:00
|
|
|
return s[:w]
|
2020-04-02 00:41:14 +08:00
|
|
|
}
|
|
|
|
|
2018-11-02 23:08:31 +08:00
|
|
|
// genSheetPasswd provides a method to generate password for worksheet
|
|
|
|
// protection by given plaintext. When an Excel sheet is being protected with
|
|
|
|
// a password, a 16-bit (two byte) long hash is generated. To verify a
|
|
|
|
// password, it is compared to the hash. Obviously, if the input data volume
|
|
|
|
// is great, numerous passwords will match the same hash. Here is the
|
|
|
|
// algorithm to create the hash value:
|
|
|
|
//
|
Huge refactorig for consistent col/row numbering (#356)
* Huge refactorig for consistent col/row numbering
Started from simply changing ToALphaString()/TitleToNumber() logic and related fixes.
But have to go deeper, do fixes, after do related fixes and again and again.
Major improvements:
1. Tests made stronger again (But still be weak).
2. "Empty" returns for incorrect input replaces with panic.
3. Check for correct col/row/cell naming & addressing by default.
4. Removed huge amount of duplicated code.
5. Removed ToALphaString(), TitleToNumber() and it helpers functions at all,
and replaced with SplitCellName(), JoinCellName(), ColumnNameToNumber(), ColumnNumberToName(), CellNameToCoordinates(), CoordinatesToCellName().
6. Minor fixes for internal variable naming for code readability (ex. col, row for input params, colIdx, rowIdx for slice indexes etc).
* Formatting fixes
2019-03-20 00:14:41 +08:00
|
|
|
// take the ASCII values of all characters shift left the first character 1 bit,
|
|
|
|
// the second 2 bits and so on (use only the lower 15 bits and rotate all higher bits,
|
|
|
|
// the highest bit of the 16-bit value is always 0 [signed short])
|
2018-11-02 23:08:31 +08:00
|
|
|
// XOR all these values
|
|
|
|
// XOR the count of characters
|
|
|
|
// XOR the constant 0xCE4B
|
|
|
|
func genSheetPasswd(plaintext string) string {
|
|
|
|
var password int64 = 0x0000
|
|
|
|
var charPos uint = 1
|
|
|
|
for _, v := range plaintext {
|
|
|
|
value := int64(v) << charPos
|
|
|
|
charPos++
|
|
|
|
rotatedBits := value >> 15 // rotated bits beyond bit 15
|
|
|
|
value &= 0x7fff // first 15 bits
|
2022-03-24 00:19:30 +08:00
|
|
|
password ^= value | rotatedBits
|
2018-11-02 23:08:31 +08:00
|
|
|
}
|
|
|
|
password ^= int64(len(plaintext))
|
|
|
|
password ^= 0xCE4B
|
|
|
|
return strings.ToUpper(strconv.FormatInt(password, 16))
|
|
|
|
}
|
2020-05-03 18:44:43 +08:00
|
|
|
|
2020-07-18 15:15:16 +08:00
|
|
|
// getRootElement extract root element attributes by given XML decoder.
|
|
|
|
func getRootElement(d *xml.Decoder) []xml.Attr {
|
|
|
|
tokenIdx := 0
|
|
|
|
for {
|
|
|
|
token, _ := d.Token()
|
|
|
|
if token == nil {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
switch startElement := token.(type) {
|
|
|
|
case xml.StartElement:
|
|
|
|
tokenIdx++
|
|
|
|
if tokenIdx == 1 {
|
|
|
|
return startElement.Attr
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// genXMLNamespace generate serialized XML attributes with a multi namespace
|
|
|
|
// by given element attributes.
|
|
|
|
func genXMLNamespace(attr []xml.Attr) string {
|
|
|
|
var rootElement string
|
|
|
|
for _, v := range attr {
|
|
|
|
if lastSpace := getXMLNamespace(v.Name.Space, attr); lastSpace != "" {
|
2021-04-30 00:14:42 +08:00
|
|
|
if lastSpace == NameSpaceXML {
|
|
|
|
lastSpace = "xml"
|
|
|
|
}
|
2020-07-18 15:15:16 +08:00
|
|
|
rootElement += fmt.Sprintf("%s:%s=\"%s\" ", lastSpace, v.Name.Local, v.Value)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
rootElement += fmt.Sprintf("%s=\"%s\" ", v.Name.Local, v.Value)
|
|
|
|
}
|
|
|
|
return strings.TrimSpace(rootElement) + ">"
|
|
|
|
}
|
|
|
|
|
|
|
|
// getXMLNamespace extract XML namespace from specified element name and attributes.
|
|
|
|
func getXMLNamespace(space string, attr []xml.Attr) string {
|
|
|
|
for _, attribute := range attr {
|
|
|
|
if attribute.Value == space {
|
|
|
|
return attribute.Name.Local
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return space
|
|
|
|
}
|
|
|
|
|
|
|
|
// replaceNameSpaceBytes provides a function to replace the XML root element
|
|
|
|
// attribute by the given component part path and XML content.
|
|
|
|
func (f *File) replaceNameSpaceBytes(path string, contentMarshal []byte) []byte {
|
2022-10-28 00:31:55 +08:00
|
|
|
sourceXmlns := []byte(`xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">`)
|
|
|
|
targetXmlns := []byte(templateNamespaceIDMap)
|
2020-07-18 15:15:16 +08:00
|
|
|
if attr, ok := f.xmlAttr[path]; ok {
|
2022-10-28 00:31:55 +08:00
|
|
|
targetXmlns = []byte(genXMLNamespace(attr))
|
2020-07-18 15:15:16 +08:00
|
|
|
}
|
2022-10-28 00:31:55 +08:00
|
|
|
return bytesReplace(contentMarshal, sourceXmlns, bytes.ReplaceAll(targetXmlns, []byte(" mc:Ignorable=\"r\""), []byte{}), -1)
|
2020-07-18 15:15:16 +08:00
|
|
|
}
|
|
|
|
|
2022-04-04 00:21:33 +08:00
|
|
|
// addNameSpaces provides a function to add an XML attribute by the given
|
2020-07-18 15:15:16 +08:00
|
|
|
// component part path.
|
|
|
|
func (f *File) addNameSpaces(path string, ns xml.Attr) {
|
|
|
|
exist := false
|
|
|
|
mc := false
|
2020-07-20 00:05:37 +08:00
|
|
|
ignore := -1
|
2020-07-18 15:15:16 +08:00
|
|
|
if attr, ok := f.xmlAttr[path]; ok {
|
2020-07-20 00:05:37 +08:00
|
|
|
for i, attribute := range attr {
|
2020-07-18 15:15:16 +08:00
|
|
|
if attribute.Name.Local == ns.Name.Local && attribute.Name.Space == ns.Name.Space {
|
|
|
|
exist = true
|
|
|
|
}
|
2020-07-20 00:05:37 +08:00
|
|
|
if attribute.Name.Local == "Ignorable" && getXMLNamespace(attribute.Name.Space, attr) == "mc" {
|
|
|
|
ignore = i
|
2020-07-18 15:15:16 +08:00
|
|
|
}
|
|
|
|
if attribute.Name.Local == "mc" && attribute.Name.Space == "xmlns" {
|
|
|
|
mc = true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if !exist {
|
|
|
|
f.xmlAttr[path] = append(f.xmlAttr[path], ns)
|
|
|
|
if !mc {
|
2020-07-19 00:10:42 +08:00
|
|
|
f.xmlAttr[path] = append(f.xmlAttr[path], SourceRelationshipCompatibility)
|
2020-07-18 15:15:16 +08:00
|
|
|
}
|
2020-07-20 00:05:37 +08:00
|
|
|
if ignore == -1 {
|
2020-07-18 15:15:16 +08:00
|
|
|
f.xmlAttr[path] = append(f.xmlAttr[path], xml.Attr{
|
|
|
|
Name: xml.Name{Local: "Ignorable", Space: "mc"},
|
|
|
|
Value: ns.Name.Local,
|
|
|
|
})
|
2020-07-20 00:05:37 +08:00
|
|
|
return
|
2020-07-18 15:15:16 +08:00
|
|
|
}
|
2020-07-20 00:05:37 +08:00
|
|
|
f.setIgnorableNameSpace(path, ignore, ns)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-01-27 13:51:47 +08:00
|
|
|
// setIgnorableNameSpace provides a function to set XML namespace as ignorable
|
|
|
|
// by the given attribute.
|
2020-07-20 00:05:37 +08:00
|
|
|
func (f *File) setIgnorableNameSpace(path string, index int, ns xml.Attr) {
|
|
|
|
ignorableNS := []string{"c14", "cdr14", "a14", "pic14", "x14", "xdr14", "x14ac", "dsp", "mso14", "dgm14", "x15", "x12ac", "x15ac", "xr", "xr2", "xr3", "xr4", "xr5", "xr6", "xr7", "xr8", "xr9", "xr10", "xr11", "xr12", "xr13", "xr14", "xr15", "x15", "x16", "x16r2", "mo", "mx", "mv", "o", "v"}
|
2022-02-13 00:06:30 +08:00
|
|
|
if inStrSlice(strings.Fields(f.xmlAttr[path][index].Value), ns.Name.Local, true) == -1 && inStrSlice(ignorableNS, ns.Name.Local, true) != -1 {
|
2020-07-20 00:05:37 +08:00
|
|
|
f.xmlAttr[path][index].Value = strings.TrimSpace(fmt.Sprintf("%s %s", f.xmlAttr[path][index].Value, ns.Name.Local))
|
2020-07-18 15:15:16 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// addSheetNameSpace add XML attribute for worksheet.
|
|
|
|
func (f *File) addSheetNameSpace(sheet string, ns xml.Attr) {
|
2022-07-18 00:21:34 +08:00
|
|
|
name, _ := f.getSheetXMLPath(sheet)
|
2020-07-18 15:15:16 +08:00
|
|
|
f.addNameSpaces(name, ns)
|
|
|
|
}
|
|
|
|
|
2021-01-27 13:51:47 +08:00
|
|
|
// isNumeric determines whether an expression is a valid numeric type and get
|
|
|
|
// the precision for the numeric.
|
2022-09-28 00:04:17 +08:00
|
|
|
func isNumeric(s string) (bool, int, float64) {
|
2022-10-12 00:06:09 +08:00
|
|
|
if strings.Contains(s, "_") {
|
|
|
|
return false, 0, 0
|
|
|
|
}
|
2022-09-28 00:04:17 +08:00
|
|
|
var decimal big.Float
|
|
|
|
_, ok := decimal.SetString(s)
|
|
|
|
if !ok {
|
|
|
|
return false, 0, 0
|
2021-01-27 13:51:47 +08:00
|
|
|
}
|
2022-09-28 00:04:17 +08:00
|
|
|
var noScientificNotation string
|
|
|
|
flt, _ := decimal.Float64()
|
|
|
|
noScientificNotation = strconv.FormatFloat(flt, 'f', -1, 64)
|
|
|
|
return true, len(strings.ReplaceAll(noScientificNotation, ".", "")), flt
|
2021-01-27 13:51:47 +08:00
|
|
|
}
|
|
|
|
|
2021-06-16 23:03:50 +08:00
|
|
|
var (
|
2022-12-07 00:45:27 +08:00
|
|
|
bstrExp = regexp.MustCompile(`_x[a-fA-F\d]{4}_`)
|
|
|
|
bstrEscapeExp = regexp.MustCompile(`x[a-fA-F\d]{4}_`)
|
2021-06-16 23:03:50 +08:00
|
|
|
)
|
|
|
|
|
2021-06-11 22:48:37 +08:00
|
|
|
// bstrUnmarshal parses the binary basic string, this will trim escaped string
|
|
|
|
// literal which not permitted in an XML 1.0 document. The basic string
|
2022-04-04 00:21:33 +08:00
|
|
|
// variant type can store any valid Unicode character. Unicode's characters
|
2021-06-11 22:48:37 +08:00
|
|
|
// that cannot be directly represented in XML as defined by the XML 1.0
|
|
|
|
// specification, shall be escaped using the Unicode numerical character
|
|
|
|
// representation escape character format _xHHHH_, where H represents a
|
|
|
|
// hexadecimal character in the character's value. For example: The Unicode
|
|
|
|
// character 8 is not permitted in an XML 1.0 document, so it shall be
|
|
|
|
// escaped as _x0008_. To store the literal form of an escape sequence, the
|
|
|
|
// initial underscore shall itself be escaped (i.e. stored as _x005F_). For
|
|
|
|
// example: The string literal _x0008_ would be stored as _x005F_x0008_.
|
|
|
|
func bstrUnmarshal(s string) (result string) {
|
2021-06-12 08:49:18 +08:00
|
|
|
matches, l, cursor := bstrExp.FindAllStringSubmatchIndex(s, -1), len(s), 0
|
2021-06-11 22:48:37 +08:00
|
|
|
for _, match := range matches {
|
|
|
|
result += s[cursor:match[0]]
|
2021-06-12 08:49:18 +08:00
|
|
|
subStr := s[match[0]:match[1]]
|
|
|
|
if subStr == "_x005F_" {
|
2021-06-13 11:23:52 +08:00
|
|
|
cursor = match[1]
|
|
|
|
result += "_"
|
|
|
|
continue
|
2021-06-11 22:48:37 +08:00
|
|
|
}
|
2021-06-12 08:49:18 +08:00
|
|
|
if bstrExp.MatchString(subStr) {
|
2021-06-13 11:23:52 +08:00
|
|
|
cursor = match[1]
|
2022-12-07 00:45:27 +08:00
|
|
|
v, _ := strconv.Unquote(`"\u` + s[match[0]+2:match[1]-1] + `"`)
|
2021-08-28 09:23:44 +08:00
|
|
|
result += v
|
2021-06-11 22:48:37 +08:00
|
|
|
}
|
|
|
|
}
|
2021-06-12 08:49:18 +08:00
|
|
|
if cursor < l {
|
2021-06-11 22:48:37 +08:00
|
|
|
result += s[cursor:]
|
|
|
|
}
|
|
|
|
return result
|
|
|
|
}
|
|
|
|
|
2021-06-16 23:03:50 +08:00
|
|
|
// bstrMarshal encode the escaped string literal which not permitted in an XML
|
|
|
|
// 1.0 document.
|
|
|
|
func bstrMarshal(s string) (result string) {
|
|
|
|
matches, l, cursor := bstrExp.FindAllStringSubmatchIndex(s, -1), len(s), 0
|
|
|
|
for _, match := range matches {
|
|
|
|
result += s[cursor:match[0]]
|
|
|
|
subStr := s[match[0]:match[1]]
|
|
|
|
if subStr == "_x005F_" {
|
|
|
|
cursor = match[1]
|
|
|
|
if match[1]+6 <= l && bstrEscapeExp.MatchString(s[match[1]:match[1]+6]) {
|
|
|
|
_, err := strconv.Unquote(`"\u` + s[match[1]+1:match[1]+5] + `"`)
|
|
|
|
if err == nil {
|
|
|
|
result += subStr + "x005F" + subStr
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
}
|
|
|
|
result += subStr + "x005F_"
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
if bstrExp.MatchString(subStr) {
|
|
|
|
cursor = match[1]
|
2022-12-07 00:45:27 +08:00
|
|
|
if _, err := strconv.Unquote(`"\u` + s[match[0]+2:match[1]-1] + `"`); err == nil {
|
2021-06-16 23:03:50 +08:00
|
|
|
result += "_x005F" + subStr
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if cursor < l {
|
|
|
|
result += s[cursor:]
|
|
|
|
}
|
|
|
|
return result
|
|
|
|
}
|
|
|
|
|
2020-05-03 18:44:43 +08:00
|
|
|
// Stack defined an abstract data type that serves as a collection of elements.
|
|
|
|
type Stack struct {
|
|
|
|
list *list.List
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewStack create a new stack.
|
|
|
|
func NewStack() *Stack {
|
2022-03-24 00:19:30 +08:00
|
|
|
l := list.New()
|
|
|
|
return &Stack{l}
|
2020-05-03 18:44:43 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// Push a value onto the top of the stack.
|
|
|
|
func (stack *Stack) Push(value interface{}) {
|
|
|
|
stack.list.PushBack(value)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Pop the top item of the stack and return it.
|
|
|
|
func (stack *Stack) Pop() interface{} {
|
|
|
|
e := stack.list.Back()
|
|
|
|
if e != nil {
|
|
|
|
stack.list.Remove(e)
|
|
|
|
return e.Value
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Peek view the top item on the stack.
|
|
|
|
func (stack *Stack) Peek() interface{} {
|
|
|
|
e := stack.list.Back()
|
|
|
|
if e != nil {
|
|
|
|
return e.Value
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Len return the number of items in the stack.
|
|
|
|
func (stack *Stack) Len() int {
|
|
|
|
return stack.list.Len()
|
|
|
|
}
|
|
|
|
|
|
|
|
// Empty the stack.
|
|
|
|
func (stack *Stack) Empty() bool {
|
|
|
|
return stack.list.Len() == 0
|
|
|
|
}
|