lib.go 8.2 KB

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