reftable.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package xlsx
  2. type RefTable struct {
  3. indexedStrings []string
  4. knownStrings map[string]int
  5. isWrite bool
  6. }
  7. // NewSharedStringRefTable() creates a new, empty RefTable.
  8. func NewSharedStringRefTable() *RefTable {
  9. rt := RefTable{}
  10. rt.knownStrings = make(map[string]int)
  11. return &rt
  12. }
  13. // MakeSharedStringRefTable() takes an xlsxSST struct and converts
  14. // it's contents to an slice of strings used to refer to string values
  15. // by numeric index - this is the model used within XLSX worksheet (a
  16. // numeric reference is stored to a shared cell value).
  17. func MakeSharedStringRefTable(source *xlsxSST) *RefTable {
  18. reftable := NewSharedStringRefTable()
  19. reftable.isWrite = false
  20. for _, si := range source.SI {
  21. if len(si.R) > 0 {
  22. newString := ""
  23. for j := 0; j < len(si.R); j++ {
  24. newString = newString + si.R[j].T
  25. }
  26. reftable.AddString(newString)
  27. } else {
  28. reftable.AddString(si.T)
  29. }
  30. }
  31. return reftable
  32. }
  33. // makeXlsxSST() takes a RefTable and returns and
  34. // equivalent xlsxSST representation.
  35. func (rt *RefTable) makeXLSXSST() xlsxSST {
  36. sst := xlsxSST{}
  37. sst.Count = len(rt.indexedStrings)
  38. sst.UniqueCount = sst.Count
  39. for _, ref := range rt.indexedStrings {
  40. si := xlsxSI{}
  41. si.T = ref
  42. sst.SI = append(sst.SI, si)
  43. }
  44. return sst
  45. }
  46. // Resolvesharedstring() looks up a string value by numeric index from
  47. // a provided reference table (just a slice of strings in the correct
  48. // order). This function only exists to provide clarity or purpose
  49. // via it's name.
  50. func (rt *RefTable) ResolveSharedString(index int) string {
  51. return rt.indexedStrings[index]
  52. }
  53. // AddString adds a string to the reference table and return it's
  54. // numeric index. If the string already exists then it simply returns
  55. // the existing index.
  56. func (rt *RefTable) AddString(str string) int {
  57. if rt.isWrite {
  58. index, ok := rt.knownStrings[str]
  59. if ok {
  60. return index
  61. }
  62. }
  63. rt.indexedStrings = append(rt.indexedStrings, str)
  64. index := len(rt.indexedStrings) - 1
  65. rt.knownStrings[str] = index
  66. return index
  67. }
  68. func (rt *RefTable) Length() int {
  69. return len(rt.indexedStrings)
  70. }