sheet.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. MaxRow int
  12. MaxCol int
  13. }
  14. // Add a new Row to a Sheet
  15. func (s *Sheet) AddRow() *Row {
  16. row := &Row{}
  17. s.Rows = append(s.Rows, row)
  18. if len(s.Rows) > s.MaxRow {
  19. s.MaxRow = len(s.Rows)
  20. }
  21. return row
  22. }
  23. // Get a Cell by passing it's cartesian coordinates (zero based) as
  24. // row and column integer indexes.
  25. //
  26. // For example:
  27. //
  28. // cell := sheet.Cell(0,0)
  29. //
  30. // ... would set the variable "cell" to contain a Cell struct
  31. // containing the data from the field "A1" on the spreadsheet.
  32. func (sh *Sheet) Cell(row, col int) *Cell {
  33. if len(sh.Rows) > row && sh.Rows[row] != nil && len(sh.Rows[row].Cells) > col {
  34. return sh.Rows[row].Cells[col]
  35. }
  36. return new(Cell)
  37. }
  38. // Dump sheet to it's XML representation, intended for internal use only
  39. func (s *Sheet) makeXLSXSheet(refTable *RefTable, styles *xlsxStyles) *xlsxWorksheet {
  40. worksheet := &xlsxWorksheet{}
  41. xSheet := xlsxSheetData{}
  42. maxRow := 0
  43. maxCell := 0
  44. for r, row := range s.Rows {
  45. if r > maxRow {
  46. maxRow = r
  47. }
  48. xRow := xlsxRow{}
  49. xRow.R = r + 1
  50. for c, cell := range row.Cells {
  51. style := cell.GetStyle()
  52. xFont, xFill, xBorder, xCellStyleXf, xCellXf := style.makeXLSXStyleElements()
  53. styles.addFont(xFont)
  54. styles.addFill(xFill)
  55. styles.addBorder(xBorder)
  56. styles.addCellStyleXf(xCellStyleXf)
  57. styles.addCellXf(xCellXf)
  58. if c > maxCell {
  59. maxCell = c
  60. }
  61. xC := xlsxC{}
  62. xC.R = fmt.Sprintf("%s%d", numericToLetters(c), r+1)
  63. xC.V = strconv.Itoa(refTable.AddString(cell.Value))
  64. xC.T = "s" // Hardcode string type, for now.
  65. xRow.C = append(xRow.C, xC)
  66. }
  67. xSheet.Row = append(xSheet.Row, xRow)
  68. }
  69. worksheet.SheetData = xSheet
  70. dimension := xlsxDimension{}
  71. dimension.Ref = fmt.Sprintf("A1:%s%d",
  72. numericToLetters(maxCell), maxRow+1)
  73. worksheet.Dimension = dimension
  74. return worksheet
  75. }