lib.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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.
  49. func toAlphaString(value int) string {
  50. if value < 0 {
  51. return ""
  52. }
  53. var ans string
  54. i := value
  55. for i > 0 {
  56. ans = string((i-1)%26+65) + ans
  57. i = (i - 1) / 26
  58. }
  59. return ans
  60. }
  61. // titleToNumber provides function to convert Excel sheet column title to int.
  62. func titleToNumber(s string) int {
  63. weight := 0.0
  64. sum := 0
  65. for i := len(s) - 1; i >= 0; i-- {
  66. sum = sum + (int(s[i])-int('A')+1)*int(math.Pow(26, weight))
  67. weight++
  68. }
  69. return sum - 1
  70. }
  71. // letterOnlyMapF is used in conjunction with strings.Map to return only the
  72. // characters A-Z and a-z in a string.
  73. func letterOnlyMapF(rune rune) rune {
  74. switch {
  75. case 'A' <= rune && rune <= 'Z':
  76. return rune
  77. case 'a' <= rune && rune <= 'z':
  78. return rune - 32
  79. }
  80. return -1
  81. }
  82. // intOnlyMapF is used in conjunction with strings.Map to return only the
  83. // numeric portions of a string.
  84. func intOnlyMapF(rune rune) rune {
  85. if rune >= 48 && rune < 58 {
  86. return rune
  87. }
  88. return -1
  89. }