lib.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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 files. Support reads and writes XLSX file generated by
  7. // Microsoft Excel™ 2007 and later. Support save file without losing original
  8. // charts of XLSX. This library needs Go version 1.10 or later.
  9. package excelize
  10. import (
  11. "archive/zip"
  12. "bytes"
  13. "container/list"
  14. "fmt"
  15. "io"
  16. "strconv"
  17. "strings"
  18. "unsafe"
  19. )
  20. // ReadZipReader can be used to read the spreadsheet in memory without touching the
  21. // filesystem.
  22. func ReadZipReader(r *zip.Reader) (map[string][]byte, int, error) {
  23. var err error
  24. fileList := make(map[string][]byte, len(r.File))
  25. worksheets := 0
  26. for _, v := range r.File {
  27. if fileList[v.Name], err = readFile(v); err != nil {
  28. return nil, 0, err
  29. }
  30. if strings.HasPrefix(v.Name, "xl/worksheets/sheet") {
  31. worksheets++
  32. }
  33. }
  34. return fileList, worksheets, nil
  35. }
  36. // readXML provides a function to read XML content as string.
  37. func (f *File) readXML(name string) []byte {
  38. if content, ok := f.XLSX[name]; ok {
  39. return content
  40. }
  41. return []byte{}
  42. }
  43. // saveFileList provides a function to update given file content in file list
  44. // of XLSX.
  45. func (f *File) saveFileList(name string, content []byte) {
  46. newContent := make([]byte, 0, len(XMLHeader)+len(content))
  47. newContent = append(newContent, []byte(XMLHeader)...)
  48. newContent = append(newContent, content...)
  49. f.XLSX[name] = newContent
  50. }
  51. // Read file content as string in a archive file.
  52. func readFile(file *zip.File) ([]byte, error) {
  53. rc, err := file.Open()
  54. if err != nil {
  55. return nil, err
  56. }
  57. dat := make([]byte, 0, file.FileInfo().Size())
  58. buff := bytes.NewBuffer(dat)
  59. _, _ = io.Copy(buff, rc)
  60. rc.Close()
  61. return buff.Bytes(), nil
  62. }
  63. // SplitCellName splits cell name to column name and row number.
  64. //
  65. // Example:
  66. //
  67. // excelize.SplitCellName("AK74") // return "AK", 74, nil
  68. //
  69. func SplitCellName(cell string) (string, int, error) {
  70. alpha := func(r rune) bool {
  71. return ('A' <= r && r <= 'Z') || ('a' <= r && r <= 'z')
  72. }
  73. if strings.IndexFunc(cell, alpha) == 0 {
  74. i := strings.LastIndexFunc(cell, alpha)
  75. if i >= 0 && i < len(cell)-1 {
  76. col, rowstr := cell[:i+1], cell[i+1:]
  77. if row, err := strconv.Atoi(rowstr); err == nil && row > 0 {
  78. return col, row, nil
  79. }
  80. }
  81. }
  82. return "", -1, newInvalidCellNameError(cell)
  83. }
  84. // JoinCellName joins cell name from column name and row number.
  85. func JoinCellName(col string, row int) (string, error) {
  86. normCol := strings.Map(func(rune rune) rune {
  87. switch {
  88. case 'A' <= rune && rune <= 'Z':
  89. return rune
  90. case 'a' <= rune && rune <= 'z':
  91. return rune - 32
  92. }
  93. return -1
  94. }, col)
  95. if len(col) == 0 || len(col) != len(normCol) {
  96. return "", newInvalidColumnNameError(col)
  97. }
  98. if row < 1 {
  99. return "", newInvalidRowNumberError(row)
  100. }
  101. return normCol + strconv.Itoa(row), nil
  102. }
  103. // ColumnNameToNumber provides a function to convert Excel sheet column name
  104. // to int. Column name case insensitive. The function returns an error if
  105. // column name incorrect.
  106. //
  107. // Example:
  108. //
  109. // excelize.ColumnNameToNumber("AK") // returns 37, nil
  110. //
  111. func ColumnNameToNumber(name string) (int, error) {
  112. if len(name) == 0 {
  113. return -1, newInvalidColumnNameError(name)
  114. }
  115. col := 0
  116. multi := 1
  117. for i := len(name) - 1; i >= 0; i-- {
  118. r := name[i]
  119. if r >= 'A' && r <= 'Z' {
  120. col += int(r-'A'+1) * multi
  121. } else if r >= 'a' && r <= 'z' {
  122. col += int(r-'a'+1) * multi
  123. } else {
  124. return -1, newInvalidColumnNameError(name)
  125. }
  126. multi *= 26
  127. }
  128. if col > TotalColumns {
  129. return -1, fmt.Errorf("column number exceeds maximum limit")
  130. }
  131. return col, nil
  132. }
  133. // ColumnNumberToName provides a function to convert the integer to Excel
  134. // sheet column title.
  135. //
  136. // Example:
  137. //
  138. // excelize.ColumnNumberToName(37) // returns "AK", nil
  139. //
  140. func ColumnNumberToName(num int) (string, error) {
  141. if num < 1 {
  142. return "", fmt.Errorf("incorrect column number %d", num)
  143. }
  144. var col string
  145. for num > 0 {
  146. col = string((num-1)%26+65) + col
  147. num = (num - 1) / 26
  148. }
  149. return col, nil
  150. }
  151. // CellNameToCoordinates converts alphanumeric cell name to [X, Y] coordinates
  152. // or returns an error.
  153. //
  154. // Example:
  155. //
  156. // excelize.CellNameToCoordinates("A1") // returns 1, 1, nil
  157. // excelize.CellNameToCoordinates("Z3") // returns 26, 3, nil
  158. //
  159. func CellNameToCoordinates(cell string) (int, int, error) {
  160. const msg = "cannot convert cell %q to coordinates: %v"
  161. colname, row, err := SplitCellName(cell)
  162. if err != nil {
  163. return -1, -1, fmt.Errorf(msg, cell, err)
  164. }
  165. if row > TotalRows {
  166. return -1, -1, fmt.Errorf("row number exceeds maximum limit")
  167. }
  168. col, err := ColumnNameToNumber(colname)
  169. return col, row, err
  170. }
  171. // CoordinatesToCellName converts [X, Y] coordinates to alpha-numeric cell
  172. // name or returns an error.
  173. //
  174. // Example:
  175. //
  176. // excelize.CoordinatesToCellName(1, 1) // returns "A1", nil
  177. //
  178. func CoordinatesToCellName(col, row int) (string, error) {
  179. if col < 1 || row < 1 {
  180. return "", fmt.Errorf("invalid cell coordinates [%d, %d]", col, row)
  181. }
  182. colname, err := ColumnNumberToName(col)
  183. return fmt.Sprintf("%s%d", colname, row), err
  184. }
  185. // boolPtr returns a pointer to a bool with the given value.
  186. func boolPtr(b bool) *bool { return &b }
  187. // intPtr returns a pointer to a int with the given value.
  188. func intPtr(i int) *int { return &i }
  189. // float64Ptr returns a pofloat64er to a float64 with the given value.
  190. func float64Ptr(f float64) *float64 { return &f }
  191. // stringPtr returns a pointer to a string with the given value.
  192. func stringPtr(s string) *string { return &s }
  193. // defaultTrue returns true if b is nil, or the pointed value.
  194. func defaultTrue(b *bool) bool {
  195. if b == nil {
  196. return true
  197. }
  198. return *b
  199. }
  200. // parseFormatSet provides a method to convert format string to []byte and
  201. // handle empty string.
  202. func parseFormatSet(formatSet string) []byte {
  203. if formatSet != "" {
  204. return []byte(formatSet)
  205. }
  206. return []byte("{}")
  207. }
  208. // namespaceStrictToTransitional provides a method to convert Strict and
  209. // Transitional namespaces.
  210. func namespaceStrictToTransitional(content []byte) []byte {
  211. var namespaceTranslationDic = map[string]string{
  212. StrictSourceRelationship: SourceRelationship,
  213. StrictSourceRelationshipChart: SourceRelationshipChart,
  214. StrictSourceRelationshipComments: SourceRelationshipComments,
  215. StrictSourceRelationshipImage: SourceRelationshipImage,
  216. StrictNameSpaceSpreadSheet: NameSpaceSpreadSheet,
  217. }
  218. for s, n := range namespaceTranslationDic {
  219. content = bytesReplace(content, stringToBytes(s), stringToBytes(n), -1)
  220. }
  221. return content
  222. }
  223. // stringToBytes cast a string to bytes pointer and assign the value of this
  224. // pointer.
  225. func stringToBytes(s string) []byte {
  226. return *(*[]byte)(unsafe.Pointer(&s))
  227. }
  228. // bytesReplace replace old bytes with given new.
  229. func bytesReplace(s, old, new []byte, n int) []byte {
  230. if n == 0 {
  231. return s
  232. }
  233. if len(old) < len(new) {
  234. return bytes.Replace(s, old, new, n)
  235. }
  236. if n < 0 {
  237. n = len(s)
  238. }
  239. var wid, i, j, w int
  240. for i, j = 0, 0; i < len(s) && j < n; j++ {
  241. wid = bytes.Index(s[i:], old)
  242. if wid < 0 {
  243. break
  244. }
  245. w += copy(s[w:], s[i:i+wid])
  246. w += copy(s[w:], new)
  247. i += wid + len(old)
  248. }
  249. w += copy(s[w:], s[i:])
  250. return s[0:w]
  251. }
  252. // genSheetPasswd provides a method to generate password for worksheet
  253. // protection by given plaintext. When an Excel sheet is being protected with
  254. // a password, a 16-bit (two byte) long hash is generated. To verify a
  255. // password, it is compared to the hash. Obviously, if the input data volume
  256. // is great, numerous passwords will match the same hash. Here is the
  257. // algorithm to create the hash value:
  258. //
  259. // take the ASCII values of all characters shift left the first character 1 bit,
  260. // the second 2 bits and so on (use only the lower 15 bits and rotate all higher bits,
  261. // the highest bit of the 16-bit value is always 0 [signed short])
  262. // XOR all these values
  263. // XOR the count of characters
  264. // XOR the constant 0xCE4B
  265. func genSheetPasswd(plaintext string) string {
  266. var password int64 = 0x0000
  267. var charPos uint = 1
  268. for _, v := range plaintext {
  269. value := int64(v) << charPos
  270. charPos++
  271. rotatedBits := value >> 15 // rotated bits beyond bit 15
  272. value &= 0x7fff // first 15 bits
  273. password ^= (value | rotatedBits)
  274. }
  275. password ^= int64(len(plaintext))
  276. password ^= 0xCE4B
  277. return strings.ToUpper(strconv.FormatInt(password, 16))
  278. }
  279. // Stack defined an abstract data type that serves as a collection of elements.
  280. type Stack struct {
  281. list *list.List
  282. }
  283. // NewStack create a new stack.
  284. func NewStack() *Stack {
  285. list := list.New()
  286. return &Stack{list}
  287. }
  288. // Push a value onto the top of the stack.
  289. func (stack *Stack) Push(value interface{}) {
  290. stack.list.PushBack(value)
  291. }
  292. // Pop the top item of the stack and return it.
  293. func (stack *Stack) Pop() interface{} {
  294. e := stack.list.Back()
  295. if e != nil {
  296. stack.list.Remove(e)
  297. return e.Value
  298. }
  299. return nil
  300. }
  301. // Peek view the top item on the stack.
  302. func (stack *Stack) Peek() interface{} {
  303. e := stack.list.Back()
  304. if e != nil {
  305. return e.Value
  306. }
  307. return nil
  308. }
  309. // Len return the number of items in the stack.
  310. func (stack *Stack) Len() int {
  311. return stack.list.Len()
  312. }
  313. // Empty the stack.
  314. func (stack *Stack) Empty() bool {
  315. return stack.list.Len() == 0
  316. }