lib.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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. return col, nil
  129. }
  130. // ColumnNumberToName provides a function to convert the integer to Excel
  131. // sheet column title.
  132. //
  133. // Example:
  134. //
  135. // excelize.ColumnNumberToName(37) // returns "AK", nil
  136. //
  137. func ColumnNumberToName(num int) (string, error) {
  138. if num < 1 {
  139. return "", fmt.Errorf("incorrect column number %d", num)
  140. }
  141. var col string
  142. for num > 0 {
  143. col = string((num-1)%26+65) + col
  144. num = (num - 1) / 26
  145. }
  146. return col, nil
  147. }
  148. // CellNameToCoordinates converts alphanumeric cell name to [X, Y] coordinates
  149. // or returns an error.
  150. //
  151. // Example:
  152. //
  153. // excelize.CellNameToCoordinates("A1") // returns 1, 1, nil
  154. // excelize.CellNameToCoordinates("Z3") // returns 26, 3, nil
  155. //
  156. func CellNameToCoordinates(cell string) (int, int, error) {
  157. const msg = "cannot convert cell %q to coordinates: %v"
  158. colname, row, err := SplitCellName(cell)
  159. if err != nil {
  160. return -1, -1, fmt.Errorf(msg, cell, err)
  161. }
  162. col, err := ColumnNameToNumber(colname)
  163. return col, row, err
  164. }
  165. // CoordinatesToCellName converts [X, Y] coordinates to alpha-numeric cell
  166. // name or returns an error.
  167. //
  168. // Example:
  169. //
  170. // excelize.CoordinatesToCellName(1, 1) // returns "A1", nil
  171. //
  172. func CoordinatesToCellName(col, row int) (string, error) {
  173. if col < 1 || row < 1 {
  174. return "", fmt.Errorf("invalid cell coordinates [%d, %d]", col, row)
  175. }
  176. colname, err := ColumnNumberToName(col)
  177. return fmt.Sprintf("%s%d", colname, row), err
  178. }
  179. // boolPtr returns a pointer to a bool with the given value.
  180. func boolPtr(b bool) *bool { return &b }
  181. // intPtr returns a pointer to a int with the given value.
  182. func intPtr(i int) *int { return &i }
  183. // float64Ptr returns a pofloat64er to a float64 with the given value.
  184. func float64Ptr(f float64) *float64 { return &f }
  185. // stringPtr returns a pointer to a string with the given value.
  186. func stringPtr(s string) *string { return &s }
  187. // defaultTrue returns true if b is nil, or the pointed value.
  188. func defaultTrue(b *bool) bool {
  189. if b == nil {
  190. return true
  191. }
  192. return *b
  193. }
  194. // parseFormatSet provides a method to convert format string to []byte and
  195. // handle empty string.
  196. func parseFormatSet(formatSet string) []byte {
  197. if formatSet != "" {
  198. return []byte(formatSet)
  199. }
  200. return []byte("{}")
  201. }
  202. // namespaceStrictToTransitional provides a method to convert Strict and
  203. // Transitional namespaces.
  204. func namespaceStrictToTransitional(content []byte) []byte {
  205. var namespaceTranslationDic = map[string]string{
  206. StrictSourceRelationship: SourceRelationship,
  207. StrictSourceRelationshipChart: SourceRelationshipChart,
  208. StrictSourceRelationshipComments: SourceRelationshipComments,
  209. StrictSourceRelationshipImage: SourceRelationshipImage,
  210. StrictNameSpaceSpreadSheet: NameSpaceSpreadSheet,
  211. }
  212. for s, n := range namespaceTranslationDic {
  213. content = bytesReplace(content, stringToBytes(s), stringToBytes(n), -1)
  214. }
  215. return content
  216. }
  217. // stringToBytes cast a string to bytes pointer and assign the value of this
  218. // pointer.
  219. func stringToBytes(s string) []byte {
  220. return *(*[]byte)(unsafe.Pointer(&s))
  221. }
  222. // bytesReplace replace old bytes with given new.
  223. func bytesReplace(s, old, new []byte, n int) []byte {
  224. if n == 0 {
  225. return s
  226. }
  227. if len(old) < len(new) {
  228. return bytes.Replace(s, old, new, n)
  229. }
  230. if n < 0 {
  231. n = len(s)
  232. }
  233. var wid, i, j, w int
  234. for i, j = 0, 0; i < len(s) && j < n; j++ {
  235. wid = bytes.Index(s[i:], old)
  236. if wid < 0 {
  237. break
  238. }
  239. w += copy(s[w:], s[i:i+wid])
  240. w += copy(s[w:], new)
  241. i += wid + len(old)
  242. }
  243. w += copy(s[w:], s[i:])
  244. return s[0:w]
  245. }
  246. // genSheetPasswd provides a method to generate password for worksheet
  247. // protection by given plaintext. When an Excel sheet is being protected with
  248. // a password, a 16-bit (two byte) long hash is generated. To verify a
  249. // password, it is compared to the hash. Obviously, if the input data volume
  250. // is great, numerous passwords will match the same hash. Here is the
  251. // algorithm to create the hash value:
  252. //
  253. // take the ASCII values of all characters shift left the first character 1 bit,
  254. // the second 2 bits and so on (use only the lower 15 bits and rotate all higher bits,
  255. // the highest bit of the 16-bit value is always 0 [signed short])
  256. // XOR all these values
  257. // XOR the count of characters
  258. // XOR the constant 0xCE4B
  259. func genSheetPasswd(plaintext string) string {
  260. var password int64 = 0x0000
  261. var charPos uint = 1
  262. for _, v := range plaintext {
  263. value := int64(v) << charPos
  264. charPos++
  265. rotatedBits := value >> 15 // rotated bits beyond bit 15
  266. value &= 0x7fff // first 15 bits
  267. password ^= (value | rotatedBits)
  268. }
  269. password ^= int64(len(plaintext))
  270. password ^= 0xCE4B
  271. return strings.ToUpper(strconv.FormatInt(password, 16))
  272. }
  273. // Stack defined an abstract data type that serves as a collection of elements.
  274. type Stack struct {
  275. list *list.List
  276. }
  277. // NewStack create a new stack.
  278. func NewStack() *Stack {
  279. list := list.New()
  280. return &Stack{list}
  281. }
  282. // Push a value onto the top of the stack.
  283. func (stack *Stack) Push(value interface{}) {
  284. stack.list.PushBack(value)
  285. }
  286. // Pop the top item of the stack and return it.
  287. func (stack *Stack) Pop() interface{} {
  288. e := stack.list.Back()
  289. if e != nil {
  290. stack.list.Remove(e)
  291. return e.Value
  292. }
  293. return nil
  294. }
  295. // Peek view the top item on the stack.
  296. func (stack *Stack) Peek() interface{} {
  297. e := stack.list.Back()
  298. if e != nil {
  299. return e.Value
  300. }
  301. return nil
  302. }
  303. // Len return the number of items in the stack.
  304. func (stack *Stack) Len() int {
  305. return stack.list.Len()
  306. }
  307. // Empty the stack.
  308. func (stack *Stack) Empty() bool {
  309. return stack.list.Len() == 0
  310. }