sheet.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package xlsx
  2. import (
  3. "fmt"
  4. "strconv"
  5. )
  6. // Sheet is a high level structure intended to provide user access to
  7. // the contents of a particular sheet within an XLSX file.
  8. type Sheet struct {
  9. Name string
  10. Rows []*Row
  11. Cols []*Col
  12. MaxRow int
  13. MaxCol int
  14. }
  15. // Add a new Row to a Sheet
  16. func (s *Sheet) AddRow() *Row {
  17. row := &Row{sheet: s}
  18. s.Rows = append(s.Rows, row)
  19. if len(s.Rows) > s.MaxRow {
  20. s.MaxRow = len(s.Rows)
  21. }
  22. return row
  23. }
  24. // Make sure we always have as many Cols as we do cells.
  25. func (s *Sheet) maybeAddCol(cellCount int) {
  26. if cellCount > s.MaxCol {
  27. s.Cols = append(s.Cols, &Col{Min: cellCount, Max: cellCount, Hidden: false})
  28. s.MaxCol = cellCount
  29. }
  30. }
  31. // Get a Cell by passing it's cartesian coordinates (zero based) as
  32. // row and column integer indexes.
  33. //
  34. // For example:
  35. //
  36. // cell := sheet.Cell(0,0)
  37. //
  38. // ... would set the variable "cell" to contain a Cell struct
  39. // containing the data from the field "A1" on the spreadsheet.
  40. func (sh *Sheet) Cell(row, col int) *Cell {
  41. if len(sh.Rows) > row && sh.Rows[row] != nil && len(sh.Rows[row].Cells) > col {
  42. return sh.Rows[row].Cells[col]
  43. }
  44. return new(Cell)
  45. }
  46. // Dump sheet to it's XML representation, intended for internal use only
  47. func (s *Sheet) makeXLSXSheet(refTable *RefTable) *xlsxWorksheet {
  48. worksheet := &xlsxWorksheet{}
  49. xSheet := xlsxSheetData{}
  50. maxRow := 0
  51. maxCell := 0
  52. for r, row := range s.Rows {
  53. if r > maxRow {
  54. maxRow = r
  55. }
  56. xRow := xlsxRow{}
  57. xRow.R = r + 1
  58. for c, cell := range row.Cells {
  59. if c > maxCell {
  60. maxCell = c
  61. }
  62. xC := xlsxC{}
  63. xC.R = fmt.Sprintf("%s%d", numericToLetters(c), r+1)
  64. xC.V = strconv.Itoa(refTable.AddString(cell.Value))
  65. xC.T = "s" // Hardcode string type, for now.
  66. xRow.C = append(xRow.C, xC)
  67. }
  68. xSheet.Row = append(xSheet.Row, xRow)
  69. }
  70. worksheet.Cols = xlsxCols{Col: []xlsxCol{}}
  71. for _, col := range s.Cols {
  72. worksheet.Cols.Col = append(worksheet.Cols.Col,
  73. xlsxCol{Min: col.Min,
  74. Max: col.Max,
  75. Hidden: col.Hidden,
  76. Width: 9.5})
  77. }
  78. worksheet.SheetData = xSheet
  79. dimension := xlsxDimension{}
  80. dimension.Ref = fmt.Sprintf("A1:%s%d",
  81. numericToLetters(maxCell), maxRow+1)
  82. worksheet.Dimension = dimension
  83. return worksheet
  84. }