lib.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. // Copyright 2016 - 2019 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.8 or later.
  9. package excelize
  10. import (
  11. "archive/zip"
  12. "bytes"
  13. "io"
  14. "log"
  15. "math"
  16. "strconv"
  17. "strings"
  18. "unicode"
  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)
  24. worksheets := 0
  25. for _, v := range r.File {
  26. fileList[v.Name] = readFile(v)
  27. if len(v.Name) > 18 {
  28. if v.Name[0:19] == "xl/worksheets/sheet" {
  29. worksheets++
  30. }
  31. }
  32. }
  33. return fileList, worksheets, nil
  34. }
  35. // readXML provides a function to read XML content as string.
  36. func (f *File) readXML(name string) []byte {
  37. if content, ok := f.XLSX[name]; ok {
  38. return content
  39. }
  40. return []byte{}
  41. }
  42. // saveFileList provides a function to update given file content in file list
  43. // of XLSX.
  44. func (f *File) saveFileList(name string, content []byte) {
  45. newContent := make([]byte, 0, len(XMLHeader)+len(content))
  46. newContent = append(newContent, []byte(XMLHeader)...)
  47. newContent = append(newContent, content...)
  48. f.XLSX[name] = newContent
  49. }
  50. // Read file content as string in a archive file.
  51. func readFile(file *zip.File) []byte {
  52. rc, err := file.Open()
  53. if err != nil {
  54. log.Fatal(err)
  55. }
  56. buff := bytes.NewBuffer(nil)
  57. _, _ = io.Copy(buff, rc)
  58. rc.Close()
  59. return buff.Bytes()
  60. }
  61. // ToAlphaString provides a function to convert integer to Excel sheet column
  62. // title. For example convert 36 to column title AK:
  63. //
  64. // excelize.ToAlphaString(36)
  65. //
  66. func ToAlphaString(value int) string {
  67. if value < 0 {
  68. return ""
  69. }
  70. var ans string
  71. i := value + 1
  72. for i > 0 {
  73. ans = string((i-1)%26+65) + ans
  74. i = (i - 1) / 26
  75. }
  76. return ans
  77. }
  78. // TitleToNumber provides a function to convert Excel sheet column title to
  79. // int (this function doesn't do value check currently). For example convert
  80. // AK and ak to column title 36:
  81. //
  82. // excelize.TitleToNumber("AK")
  83. // excelize.TitleToNumber("ak")
  84. //
  85. func TitleToNumber(s string) int {
  86. weight := 0.0
  87. sum := 0
  88. for i := len(s) - 1; i >= 0; i-- {
  89. ch := int(s[i])
  90. if int(s[i]) >= int('a') && int(s[i]) <= int('z') {
  91. ch = int(s[i]) - 32
  92. }
  93. sum = sum + (ch-int('A')+1)*int(math.Pow(26, weight))
  94. weight++
  95. }
  96. return sum - 1
  97. }
  98. // letterOnlyMapF is used in conjunction with strings.Map to return only the
  99. // characters A-Z and a-z in a string.
  100. func letterOnlyMapF(rune rune) rune {
  101. switch {
  102. case 'A' <= rune && rune <= 'Z':
  103. return rune
  104. case 'a' <= rune && rune <= 'z':
  105. return rune - 32
  106. }
  107. return -1
  108. }
  109. // intOnlyMapF is used in conjunction with strings.Map to return only the
  110. // numeric portions of a string.
  111. func intOnlyMapF(rune rune) rune {
  112. if rune >= 48 && rune < 58 {
  113. return rune
  114. }
  115. return -1
  116. }
  117. // boolPtr returns a pointer to a bool with the given value.
  118. func boolPtr(b bool) *bool { return &b }
  119. // defaultTrue returns true if b is nil, or the pointed value.
  120. func defaultTrue(b *bool) bool {
  121. if b == nil {
  122. return true
  123. }
  124. return *b
  125. }
  126. // axisLowerOrEqualThan returns true if axis1 <= axis2 axis1/axis2 can be
  127. // either a column or a row axis, e.g. "A", "AAE", "42", "1", etc.
  128. //
  129. // For instance, the following comparisons are all true:
  130. //
  131. // "A" <= "B"
  132. // "A" <= "AA"
  133. // "B" <= "AA"
  134. // "BC" <= "ABCD" (in a XLSX sheet, the BC col comes before the ABCD col)
  135. // "1" <= "2"
  136. // "2" <= "11" (in a XLSX sheet, the row 2 comes before the row 11)
  137. // and so on
  138. func axisLowerOrEqualThan(axis1, axis2 string) bool {
  139. if len(axis1) < len(axis2) {
  140. return true
  141. } else if len(axis1) > len(axis2) {
  142. return false
  143. } else {
  144. return axis1 <= axis2
  145. }
  146. }
  147. // getCellColRow returns the two parts of a cell identifier (its col and row)
  148. // as strings
  149. //
  150. // For instance:
  151. //
  152. // "C220" => "C", "220"
  153. // "aaef42" => "aaef", "42"
  154. // "" => "", ""
  155. func getCellColRow(cell string) (col, row string) {
  156. for index, rune := range cell {
  157. if unicode.IsDigit(rune) {
  158. return cell[:index], cell[index:]
  159. }
  160. }
  161. return cell, ""
  162. }
  163. // parseFormatSet provides a method to convert format string to []byte and
  164. // handle empty string.
  165. func parseFormatSet(formatSet string) []byte {
  166. if formatSet != "" {
  167. return []byte(formatSet)
  168. }
  169. return []byte("{}")
  170. }
  171. // namespaceStrictToTransitional provides a method to convert Strict and
  172. // Transitional namespaces.
  173. func namespaceStrictToTransitional(content []byte) []byte {
  174. var namespaceTranslationDic = map[string]string{
  175. StrictSourceRelationship: SourceRelationship,
  176. StrictSourceRelationshipChart: SourceRelationshipChart,
  177. StrictSourceRelationshipComments: SourceRelationshipComments,
  178. StrictSourceRelationshipImage: SourceRelationshipImage,
  179. StrictNameSpaceSpreadSheet: NameSpaceSpreadSheet,
  180. }
  181. for s, n := range namespaceTranslationDic {
  182. content = bytes.Replace(content, []byte(s), []byte(n), -1)
  183. }
  184. return content
  185. }
  186. // genSheetPasswd provides a method to generate password for worksheet
  187. // protection by given plaintext. When an Excel sheet is being protected with
  188. // a password, a 16-bit (two byte) long hash is generated. To verify a
  189. // password, it is compared to the hash. Obviously, if the input data volume
  190. // is great, numerous passwords will match the same hash. Here is the
  191. // algorithm to create the hash value:
  192. //
  193. // 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])
  194. // XOR all these values
  195. // XOR the count of characters
  196. // XOR the constant 0xCE4B
  197. func genSheetPasswd(plaintext string) string {
  198. var password int64 = 0x0000
  199. var charPos uint = 1
  200. for _, v := range plaintext {
  201. value := int64(v) << charPos
  202. charPos++
  203. rotatedBits := value >> 15 // rotated bits beyond bit 15
  204. value &= 0x7fff // first 15 bits
  205. password ^= (value | rotatedBits)
  206. }
  207. password ^= int64(len(plaintext))
  208. password ^= 0xCE4B
  209. return strings.ToUpper(strconv.FormatInt(password, 16))
  210. }