lib.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. package excelize
  2. import (
  3. "archive/zip"
  4. "bytes"
  5. "io"
  6. "log"
  7. "math"
  8. )
  9. // ReadZipReader can be used to read an XLSX in memory without touching the
  10. // filesystem.
  11. func ReadZipReader(r *zip.Reader) (map[string]string, int, error) {
  12. fileList := make(map[string]string)
  13. worksheets := 0
  14. for _, v := range r.File {
  15. fileList[v.Name] = readFile(v)
  16. if len(v.Name) > 18 {
  17. if v.Name[0:19] == "xl/worksheets/sheet" {
  18. worksheets++
  19. }
  20. }
  21. }
  22. return fileList, worksheets, nil
  23. }
  24. // readXML provides function to read XML content as string.
  25. func (f *File) readXML(name string) string {
  26. if content, ok := f.XLSX[name]; ok {
  27. return content
  28. }
  29. return ""
  30. }
  31. // saveFileList provides function to update given file content in file list of
  32. // XLSX.
  33. func (f *File) saveFileList(name, content string) {
  34. f.XLSX[name] = XMLHeader + content
  35. }
  36. // Read file content as string in a archive file.
  37. func readFile(file *zip.File) string {
  38. rc, err := file.Open()
  39. if err != nil {
  40. log.Fatal(err)
  41. }
  42. buff := bytes.NewBuffer(nil)
  43. io.Copy(buff, rc)
  44. rc.Close()
  45. return string(buff.Bytes())
  46. }
  47. // ToAlphaString provides function to convert integer to Excel sheet column
  48. // title. For example convert 37 to column title AK:
  49. //
  50. // excelize.ToAlphaString(37)
  51. //
  52. func ToAlphaString(value int) string {
  53. if value < 0 {
  54. return ""
  55. }
  56. var ans string
  57. i := value
  58. for i > 0 {
  59. ans = string((i-1)%26+65) + ans
  60. i = (i - 1) / 26
  61. }
  62. return ans
  63. }
  64. // titleToNumber provides function to convert Excel sheet column title to int.
  65. func titleToNumber(s string) int {
  66. weight := 0.0
  67. sum := 0
  68. for i := len(s) - 1; i >= 0; i-- {
  69. sum = sum + (int(s[i])-int('A')+1)*int(math.Pow(26, weight))
  70. weight++
  71. }
  72. return sum - 1
  73. }
  74. // letterOnlyMapF is used in conjunction with strings.Map to return only the
  75. // characters A-Z and a-z in a string.
  76. func letterOnlyMapF(rune rune) rune {
  77. switch {
  78. case 'A' <= rune && rune <= 'Z':
  79. return rune
  80. case 'a' <= rune && rune <= 'z':
  81. return rune - 32
  82. }
  83. return -1
  84. }
  85. // intOnlyMapF is used in conjunction with strings.Map to return only the
  86. // numeric portions of a string.
  87. func intOnlyMapF(rune rune) rune {
  88. if rune >= 48 && rune < 58 {
  89. return rune
  90. }
  91. return -1
  92. }