lib.go 12 KB

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