sheet.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package xlsx
  2. import (
  3. "bytes"
  4. "encoding/xml"
  5. "fmt"
  6. )
  7. // Sheet is a high level structure intended to provide user access to
  8. // the contents of a particular sheet within an XLSX file.
  9. type Sheet struct {
  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. // Dump sheet to it's XML representation
  24. func (s *Sheet) makeXLSXSheet() ([]byte, error) {
  25. worksheet := &xlsxWorksheet{}
  26. xSheet := xlsxSheetData{}
  27. maxRow := 0
  28. maxCell := 0
  29. for r, row := range s.Rows {
  30. if r > maxRow {
  31. maxRow = r
  32. }
  33. xRow := xlsxRow{}
  34. xRow.R = r + 1
  35. for c, cell := range row.Cells {
  36. if c > maxCell {
  37. maxCell = c
  38. }
  39. xC := xlsxC{}
  40. xC.R = fmt.Sprintf("%s%d", numericToLetters(c), r + 1)
  41. xC.V = cell.Value
  42. xC.T = "s" // Hardcode string type, for now.
  43. xRow.C = append(xRow.C, xC)
  44. }
  45. xSheet.Row = append(xSheet.Row, xRow)
  46. }
  47. worksheet.SheetData = xSheet
  48. dimension := xlsxDimension{}
  49. dimension.Ref = fmt.Sprintf("A1:%s%d",
  50. numericToLetters(maxCell), maxRow + 1)
  51. worksheet.Dimension = dimension
  52. output := bytes.NewBufferString(xml.Header)
  53. body, err := xml.MarshalIndent(worksheet, " ", " ")
  54. if err != nil {
  55. return nil, err
  56. }
  57. _, err = output.Write(body)
  58. if err != nil {
  59. return nil, err
  60. }
  61. return output.Bytes(), nil
  62. }