lib.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. // Copyright 2016 - 2020 The excelize Authors. All rights reserved. Use of
  2. // this source code is governed by a BSD-style license that can be found in
  3. // the LICENSE file.
  4. //
  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
  7. // spreadsheet documents generated by Microsoft Exce™ 2007 and later. Supports
  8. // complex components by high compatibility, and provided streaming API for
  9. // generating or reading data from a worksheet with huge amounts of data. This
  10. // library needs Go version 1.10 or later.
  11. package excelize
  12. import (
  13. "archive/zip"
  14. "bytes"
  15. "container/list"
  16. "encoding/xml"
  17. "fmt"
  18. "io"
  19. "strconv"
  20. "strings"
  21. )
  22. // ReadZipReader can be used to read the spreadsheet in memory without touching the
  23. // filesystem.
  24. func ReadZipReader(r *zip.Reader) (map[string][]byte, int, error) {
  25. var err error
  26. var docPart = map[string]string{
  27. "[content_types].xml": "[Content_Types].xml",
  28. "xl/sharedstrings.xml": "xl/sharedStrings.xml",
  29. }
  30. fileList := make(map[string][]byte, len(r.File))
  31. worksheets := 0
  32. for _, v := range r.File {
  33. fileName := v.Name
  34. if partName, ok := docPart[strings.ToLower(v.Name)]; ok {
  35. fileName = partName
  36. }
  37. if fileList[fileName], err = readFile(v); err != nil {
  38. return nil, 0, err
  39. }
  40. if strings.HasPrefix(v.Name, "xl/worksheets/sheet") {
  41. worksheets++
  42. }
  43. }
  44. return fileList, worksheets, nil
  45. }
  46. // readXML provides a function to read XML content as string.
  47. func (f *File) readXML(name string) []byte {
  48. if content, ok := f.XLSX[name]; ok {
  49. return content
  50. }
  51. return []byte{}
  52. }
  53. // saveFileList provides a function to update given file content in file list
  54. // of XLSX.
  55. func (f *File) saveFileList(name string, content []byte) {
  56. newContent := make([]byte, 0, len(XMLHeader)+len(content))
  57. newContent = append(newContent, []byte(XMLHeader)...)
  58. newContent = append(newContent, content...)
  59. f.XLSX[name] = newContent
  60. }
  61. // Read file content as string in a archive file.
  62. func readFile(file *zip.File) ([]byte, error) {
  63. rc, err := file.Open()
  64. if err != nil {
  65. return nil, err
  66. }
  67. dat := make([]byte, 0, file.FileInfo().Size())
  68. buff := bytes.NewBuffer(dat)
  69. _, _ = io.Copy(buff, rc)
  70. rc.Close()
  71. return buff.Bytes(), nil
  72. }
  73. // SplitCellName splits cell name to column name and row number.
  74. //
  75. // Example:
  76. //
  77. // excelize.SplitCellName("AK74") // return "AK", 74, nil
  78. //
  79. func SplitCellName(cell string) (string, int, error) {
  80. alpha := func(r rune) bool {
  81. return ('A' <= r && r <= 'Z') || ('a' <= r && r <= 'z')
  82. }
  83. if strings.IndexFunc(cell, alpha) == 0 {
  84. i := strings.LastIndexFunc(cell, alpha)
  85. if i >= 0 && i < len(cell)-1 {
  86. col, rowstr := cell[:i+1], cell[i+1:]
  87. if row, err := strconv.Atoi(rowstr); err == nil && row > 0 {
  88. return col, row, nil
  89. }
  90. }
  91. }
  92. return "", -1, newInvalidCellNameError(cell)
  93. }
  94. // JoinCellName joins cell name from column name and row number.
  95. func JoinCellName(col string, row int) (string, error) {
  96. normCol := strings.Map(func(rune rune) rune {
  97. switch {
  98. case 'A' <= rune && rune <= 'Z':
  99. return rune
  100. case 'a' <= rune && rune <= 'z':
  101. return rune - 32
  102. }
  103. return -1
  104. }, col)
  105. if len(col) == 0 || len(col) != len(normCol) {
  106. return "", newInvalidColumnNameError(col)
  107. }
  108. if row < 1 {
  109. return "", newInvalidRowNumberError(row)
  110. }
  111. return normCol + strconv.Itoa(row), nil
  112. }
  113. // ColumnNameToNumber provides a function to convert Excel sheet column name
  114. // to int. Column name case insensitive. The function returns an error if
  115. // column name incorrect.
  116. //
  117. // Example:
  118. //
  119. // excelize.ColumnNameToNumber("AK") // returns 37, nil
  120. //
  121. func ColumnNameToNumber(name string) (int, error) {
  122. if len(name) == 0 {
  123. return -1, newInvalidColumnNameError(name)
  124. }
  125. col := 0
  126. multi := 1
  127. for i := len(name) - 1; i >= 0; i-- {
  128. r := name[i]
  129. if r >= 'A' && r <= 'Z' {
  130. col += int(r-'A'+1) * multi
  131. } else if r >= 'a' && r <= 'z' {
  132. col += int(r-'a'+1) * multi
  133. } else {
  134. return -1, newInvalidColumnNameError(name)
  135. }
  136. multi *= 26
  137. }
  138. if col > TotalColumns {
  139. return -1, fmt.Errorf("column number exceeds maximum limit")
  140. }
  141. return col, nil
  142. }
  143. // ColumnNumberToName provides a function to convert the integer to Excel
  144. // sheet column title.
  145. //
  146. // Example:
  147. //
  148. // excelize.ColumnNumberToName(37) // returns "AK", nil
  149. //
  150. func ColumnNumberToName(num int) (string, error) {
  151. if num < 1 {
  152. return "", fmt.Errorf("incorrect column number %d", num)
  153. }
  154. if num > TotalColumns {
  155. return "", fmt.Errorf("column number exceeds maximum limit")
  156. }
  157. var col string
  158. for num > 0 {
  159. col = string(rune((num-1)%26+65)) + col
  160. num = (num - 1) / 26
  161. }
  162. return col, nil
  163. }
  164. // CellNameToCoordinates converts alphanumeric cell name to [X, Y] coordinates
  165. // or returns an error.
  166. //
  167. // Example:
  168. //
  169. // excelize.CellNameToCoordinates("A1") // returns 1, 1, nil
  170. // excelize.CellNameToCoordinates("Z3") // returns 26, 3, nil
  171. //
  172. func CellNameToCoordinates(cell string) (int, int, error) {
  173. const msg = "cannot convert cell %q to coordinates: %v"
  174. colname, row, err := SplitCellName(cell)
  175. if err != nil {
  176. return -1, -1, fmt.Errorf(msg, cell, err)
  177. }
  178. if row > TotalRows {
  179. return -1, -1, fmt.Errorf("row number exceeds maximum limit")
  180. }
  181. col, err := ColumnNameToNumber(colname)
  182. return col, row, err
  183. }
  184. // CoordinatesToCellName converts [X, Y] coordinates to alpha-numeric cell
  185. // name or returns an error.
  186. //
  187. // Example:
  188. //
  189. // excelize.CoordinatesToCellName(1, 1) // returns "A1", nil
  190. //
  191. func CoordinatesToCellName(col, row int) (string, error) {
  192. if col < 1 || row < 1 {
  193. return "", fmt.Errorf("invalid cell coordinates [%d, %d]", col, row)
  194. }
  195. //Using itoa will save more memory
  196. colname, err := ColumnNumberToName(col)
  197. return colname + strconv.Itoa(row), err
  198. }
  199. // boolPtr returns a pointer to a bool with the given value.
  200. func boolPtr(b bool) *bool { return &b }
  201. // intPtr returns a pointer to a int with the given value.
  202. func intPtr(i int) *int { return &i }
  203. // float64Ptr returns a pofloat64er to a float64 with the given value.
  204. func float64Ptr(f float64) *float64 { return &f }
  205. // stringPtr returns a pointer to a string with the given value.
  206. func stringPtr(s string) *string { return &s }
  207. // defaultTrue returns true if b is nil, or the pointed value.
  208. func defaultTrue(b *bool) bool {
  209. if b == nil {
  210. return true
  211. }
  212. return *b
  213. }
  214. // parseFormatSet provides a method to convert format string to []byte and
  215. // handle empty string.
  216. func parseFormatSet(formatSet string) []byte {
  217. if formatSet != "" {
  218. return []byte(formatSet)
  219. }
  220. return []byte("{}")
  221. }
  222. // namespaceStrictToTransitional provides a method to convert Strict and
  223. // Transitional namespaces.
  224. func namespaceStrictToTransitional(content []byte) []byte {
  225. var namespaceTranslationDic = map[string]string{
  226. StrictSourceRelationship: SourceRelationship.Value,
  227. StrictSourceRelationshipChart: SourceRelationshipChart,
  228. StrictSourceRelationshipComments: SourceRelationshipComments,
  229. StrictSourceRelationshipImage: SourceRelationshipImage,
  230. StrictNameSpaceSpreadSheet: NameSpaceSpreadSheet.Value,
  231. }
  232. for s, n := range namespaceTranslationDic {
  233. content = bytesReplace(content, []byte(s), []byte(n), -1)
  234. }
  235. return content
  236. }
  237. // bytesReplace replace old bytes with given new.
  238. func bytesReplace(s, old, new []byte, n int) []byte {
  239. if n == 0 {
  240. return s
  241. }
  242. if len(old) < len(new) {
  243. return bytes.Replace(s, old, new, n)
  244. }
  245. if n < 0 {
  246. n = len(s)
  247. }
  248. var wid, i, j, w int
  249. for i, j = 0, 0; i < len(s) && j < n; j++ {
  250. wid = bytes.Index(s[i:], old)
  251. if wid < 0 {
  252. break
  253. }
  254. w += copy(s[w:], s[i:i+wid])
  255. w += copy(s[w:], new)
  256. i += wid + len(old)
  257. }
  258. w += copy(s[w:], s[i:])
  259. return s[0:w]
  260. }
  261. // genSheetPasswd provides a method to generate password for worksheet
  262. // protection by given plaintext. When an Excel sheet is being protected with
  263. // a password, a 16-bit (two byte) long hash is generated. To verify a
  264. // password, it is compared to the hash. Obviously, if the input data volume
  265. // is great, numerous passwords will match the same hash. Here is the
  266. // algorithm to create the hash value:
  267. //
  268. // take the ASCII values of all characters shift left the first character 1 bit,
  269. // the second 2 bits and so on (use only the lower 15 bits and rotate all higher bits,
  270. // the highest bit of the 16-bit value is always 0 [signed short])
  271. // XOR all these values
  272. // XOR the count of characters
  273. // XOR the constant 0xCE4B
  274. func genSheetPasswd(plaintext string) string {
  275. var password int64 = 0x0000
  276. var charPos uint = 1
  277. for _, v := range plaintext {
  278. value := int64(v) << charPos
  279. charPos++
  280. rotatedBits := value >> 15 // rotated bits beyond bit 15
  281. value &= 0x7fff // first 15 bits
  282. password ^= (value | rotatedBits)
  283. }
  284. password ^= int64(len(plaintext))
  285. password ^= 0xCE4B
  286. return strings.ToUpper(strconv.FormatInt(password, 16))
  287. }
  288. // getRootElement extract root element attributes by given XML decoder.
  289. func getRootElement(d *xml.Decoder) []xml.Attr {
  290. tokenIdx := 0
  291. for {
  292. token, _ := d.Token()
  293. if token == nil {
  294. break
  295. }
  296. switch startElement := token.(type) {
  297. case xml.StartElement:
  298. tokenIdx++
  299. if tokenIdx == 1 {
  300. return startElement.Attr
  301. }
  302. }
  303. }
  304. return nil
  305. }
  306. // genXMLNamespace generate serialized XML attributes with a multi namespace
  307. // by given element attributes.
  308. func genXMLNamespace(attr []xml.Attr) string {
  309. var rootElement string
  310. for _, v := range attr {
  311. if lastSpace := getXMLNamespace(v.Name.Space, attr); lastSpace != "" {
  312. rootElement += fmt.Sprintf("%s:%s=\"%s\" ", lastSpace, v.Name.Local, v.Value)
  313. continue
  314. }
  315. rootElement += fmt.Sprintf("%s=\"%s\" ", v.Name.Local, v.Value)
  316. }
  317. return strings.TrimSpace(rootElement) + ">"
  318. }
  319. // getXMLNamespace extract XML namespace from specified element name and attributes.
  320. func getXMLNamespace(space string, attr []xml.Attr) string {
  321. for _, attribute := range attr {
  322. if attribute.Value == space {
  323. return attribute.Name.Local
  324. }
  325. }
  326. return space
  327. }
  328. // replaceNameSpaceBytes provides a function to replace the XML root element
  329. // attribute by the given component part path and XML content.
  330. func (f *File) replaceNameSpaceBytes(path string, contentMarshal []byte) []byte {
  331. var oldXmlns = []byte(`xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">`)
  332. var newXmlns = []byte(templateNamespaceIDMap)
  333. if attr, ok := f.xmlAttr[path]; ok {
  334. newXmlns = []byte(genXMLNamespace(attr))
  335. }
  336. return bytesReplace(contentMarshal, oldXmlns, newXmlns, -1)
  337. }
  338. // addNameSpaces provides a function to add a XML attribute by the given
  339. // component part path.
  340. func (f *File) addNameSpaces(path string, ns xml.Attr) {
  341. exist := false
  342. mc := false
  343. ignore := -1
  344. if attr, ok := f.xmlAttr[path]; ok {
  345. for i, attribute := range attr {
  346. if attribute.Name.Local == ns.Name.Local && attribute.Name.Space == ns.Name.Space {
  347. exist = true
  348. }
  349. if attribute.Name.Local == "Ignorable" && getXMLNamespace(attribute.Name.Space, attr) == "mc" {
  350. ignore = i
  351. }
  352. if attribute.Name.Local == "mc" && attribute.Name.Space == "xmlns" {
  353. mc = true
  354. }
  355. }
  356. }
  357. if !exist {
  358. f.xmlAttr[path] = append(f.xmlAttr[path], ns)
  359. if !mc {
  360. f.xmlAttr[path] = append(f.xmlAttr[path], SourceRelationshipCompatibility)
  361. }
  362. if ignore == -1 {
  363. f.xmlAttr[path] = append(f.xmlAttr[path], xml.Attr{
  364. Name: xml.Name{Local: "Ignorable", Space: "mc"},
  365. Value: ns.Name.Local,
  366. })
  367. return
  368. }
  369. f.setIgnorableNameSpace(path, ignore, ns)
  370. }
  371. }
  372. // setIgnorableNameSpace provides a function to set XML namespace as ignorable by the given
  373. // attribute.
  374. func (f *File) setIgnorableNameSpace(path string, index int, ns xml.Attr) {
  375. 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"}
  376. if inStrSlice(strings.Fields(f.xmlAttr[path][index].Value), ns.Name.Local) == -1 && inStrSlice(ignorableNS, ns.Name.Local) != -1 {
  377. f.xmlAttr[path][index].Value = strings.TrimSpace(fmt.Sprintf("%s %s", f.xmlAttr[path][index].Value, ns.Name.Local))
  378. }
  379. }
  380. // addSheetNameSpace add XML attribute for worksheet.
  381. func (f *File) addSheetNameSpace(sheet string, ns xml.Attr) {
  382. name, _ := f.sheetMap[trimSheetName(sheet)]
  383. f.addNameSpaces(name, ns)
  384. }
  385. // Stack defined an abstract data type that serves as a collection of elements.
  386. type Stack struct {
  387. list *list.List
  388. }
  389. // NewStack create a new stack.
  390. func NewStack() *Stack {
  391. list := list.New()
  392. return &Stack{list}
  393. }
  394. // Push a value onto the top of the stack.
  395. func (stack *Stack) Push(value interface{}) {
  396. stack.list.PushBack(value)
  397. }
  398. // Pop the top item of the stack and return it.
  399. func (stack *Stack) Pop() interface{} {
  400. e := stack.list.Back()
  401. if e != nil {
  402. stack.list.Remove(e)
  403. return e.Value
  404. }
  405. return nil
  406. }
  407. // Peek view the top item on the stack.
  408. func (stack *Stack) Peek() interface{} {
  409. e := stack.list.Back()
  410. if e != nil {
  411. return e.Value
  412. }
  413. return nil
  414. }
  415. // Len return the number of items in the stack.
  416. func (stack *Stack) Len() int {
  417. return stack.list.Len()
  418. }
  419. // Empty the stack.
  420. func (stack *Stack) Empty() bool {
  421. return stack.list.Len() == 0
  422. }