sheet.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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. File *File
  11. Rows []*Row
  12. Cols []*Col
  13. MaxRow int
  14. MaxCol int
  15. Hidden bool
  16. Selected bool
  17. SheetViews []SheetView
  18. SheetFormat SheetFormat
  19. }
  20. type SheetView struct {
  21. Pane *Pane
  22. }
  23. type Pane struct {
  24. XSplit float64
  25. YSplit float64
  26. TopLeftCell string
  27. ActivePane string
  28. State string // Either "split" or "frozen"
  29. }
  30. type SheetFormat struct {
  31. DefaultColWidth float64
  32. DefaultRowHeight float64
  33. }
  34. // Add a new Row to a Sheet
  35. func (s *Sheet) AddRow() *Row {
  36. row := &Row{Sheet: s}
  37. s.Rows = append(s.Rows, row)
  38. if len(s.Rows) > s.MaxRow {
  39. s.MaxRow = len(s.Rows)
  40. }
  41. return row
  42. }
  43. // Make sure we always have as many Cols as we do cells.
  44. func (s *Sheet) maybeAddCol(cellCount int) {
  45. if cellCount > s.MaxCol {
  46. col := &Col{
  47. style: NewStyle(),
  48. Min: cellCount,
  49. Max: cellCount,
  50. Hidden: false,
  51. Collapsed: false}
  52. s.Cols = append(s.Cols, col)
  53. s.MaxCol = cellCount
  54. }
  55. }
  56. // Make sure we always have as many Cols as we do cells.
  57. func (s *Sheet) Col(idx int) *Col {
  58. s.maybeAddCol(idx + 1)
  59. return s.Cols[idx]
  60. }
  61. // Get a Cell by passing it's cartesian coordinates (zero based) as
  62. // row and column integer indexes.
  63. //
  64. // For example:
  65. //
  66. // cell := sheet.Cell(0,0)
  67. //
  68. // ... would set the variable "cell" to contain a Cell struct
  69. // containing the data from the field "A1" on the spreadsheet.
  70. func (sh *Sheet) Cell(row, col int) *Cell {
  71. // If the user requests a row beyond what we have, then extend.
  72. for len(sh.Rows) <= row {
  73. sh.AddRow()
  74. }
  75. r := sh.Rows[row]
  76. for len(r.Cells) <= col {
  77. r.AddCell()
  78. }
  79. return r.Cells[col]
  80. }
  81. //Set the width of a single column or multiple columns.
  82. func (s *Sheet) SetColWidth(startcol, endcol int, width float64) error {
  83. if startcol > endcol {
  84. return fmt.Errorf("Could not set width for range %d-%d: startcol must be less than endcol.", startcol, endcol)
  85. }
  86. col := &Col{
  87. style: NewStyle(),
  88. Min: startcol + 1,
  89. Max: endcol + 1,
  90. Hidden: false,
  91. Collapsed: false,
  92. Width: width}
  93. s.Cols = append(s.Cols, col)
  94. if endcol+1 > s.MaxCol {
  95. s.MaxCol = endcol + 1
  96. }
  97. return nil
  98. }
  99. // When merging cells, the cell may be the 'original' or the 'covered'.
  100. // First, figure out which cells are merge starting points. Then create
  101. // the necessary cells underlying the merge area.
  102. // Then go through all the underlying cells and apply the appropriate
  103. // border, based on the original cell.
  104. func (s *Sheet) handleMerged() {
  105. merged := make(map[string]*Cell)
  106. for r, row := range s.Rows {
  107. for c, cell := range row.Cells {
  108. if cell.HMerge > 0 || cell.VMerge > 0 {
  109. coord := fmt.Sprintf("%s%d", numericToLetters(c), r+1)
  110. merged[coord] = cell
  111. }
  112. }
  113. }
  114. // This loop iterates over all cells that should be merged and applies the correct
  115. // borders to them depending on their position. If any cells required by the merge
  116. // are missing, they will be allocated by s.Cell().
  117. for key, cell := range merged {
  118. mainstyle := cell.GetStyle()
  119. top := mainstyle.Border.Top
  120. left := mainstyle.Border.Left
  121. right := mainstyle.Border.Right
  122. bottom := mainstyle.Border.Bottom
  123. // When merging cells, the upper left cell does not maintain
  124. // the original borders
  125. mainstyle.Border.Top = ""
  126. mainstyle.Border.Left = ""
  127. mainstyle.Border.Right = ""
  128. mainstyle.Border.Bottom = ""
  129. maincol, mainrow, _ := getCoordsFromCellIDString(key)
  130. for rownum := 0; rownum <= cell.VMerge; rownum++ {
  131. for colnum := 0; colnum <= cell.HMerge; colnum++ {
  132. tmpcell := s.Cell(mainrow+rownum, maincol+colnum)
  133. style := tmpcell.GetStyle()
  134. style.ApplyBorder = true
  135. if rownum == 0 {
  136. style.Border.Top = top
  137. }
  138. if rownum == (cell.VMerge) {
  139. style.Border.Bottom = bottom
  140. }
  141. if colnum == 0 {
  142. style.Border.Left = left
  143. }
  144. if colnum == (cell.HMerge) {
  145. style.Border.Right = right
  146. }
  147. }
  148. }
  149. }
  150. }
  151. // Dump sheet to its XML representation, intended for internal use only
  152. func (s *Sheet) makeXLSXSheet(refTable *RefTable, styles *xlsxStyleSheet) *xlsxWorksheet {
  153. worksheet := newXlsxWorksheet()
  154. xSheet := xlsxSheetData{}
  155. maxRow := 0
  156. maxCell := 0
  157. // Scan through the sheet and see if there are any merged cells. If there
  158. // are, we may need to extend the size of the sheet. There needs to be
  159. // phantom cells underlying the area covered by the merged cell
  160. s.handleMerged()
  161. if s.Selected {
  162. worksheet.SheetViews.SheetView[0].TabSelected = true
  163. }
  164. if s.SheetFormat.DefaultRowHeight != 0 {
  165. worksheet.SheetFormatPr.DefaultRowHeight = s.SheetFormat.DefaultRowHeight
  166. }
  167. worksheet.SheetFormatPr.DefaultColWidth = s.SheetFormat.DefaultColWidth
  168. colsXfIdList := make([]int, len(s.Cols))
  169. worksheet.Cols = &xlsxCols{Col: []xlsxCol{}}
  170. for c, col := range s.Cols {
  171. XfId := 0
  172. if col.Min == 0 {
  173. col.Min = 1
  174. }
  175. if col.Max == 0 {
  176. col.Max = 1
  177. }
  178. style := col.GetStyle()
  179. //col's style always not nil
  180. if style != nil {
  181. xNumFmt := styles.newNumFmt(col.numFmt)
  182. XfId = handleStyleForXLSX(style, xNumFmt.NumFmtId, styles)
  183. }
  184. colsXfIdList[c] = XfId
  185. var customWidth int
  186. if col.Width == 0 {
  187. col.Width = ColWidth
  188. } else {
  189. customWidth = 1
  190. }
  191. worksheet.Cols.Col = append(worksheet.Cols.Col,
  192. xlsxCol{Min: col.Min,
  193. Max: col.Max,
  194. Hidden: col.Hidden,
  195. Width: col.Width,
  196. CustomWidth: customWidth,
  197. Collapsed: col.Collapsed,
  198. Style: XfId,
  199. })
  200. }
  201. for r, row := range s.Rows {
  202. if r > maxRow {
  203. maxRow = r
  204. }
  205. xRow := xlsxRow{}
  206. xRow.R = r + 1
  207. if row.isCustom {
  208. xRow.CustomHeight = true
  209. xRow.Ht = fmt.Sprintf("%g", row.Height)
  210. }
  211. for c, cell := range row.Cells {
  212. XfId := colsXfIdList[c]
  213. // generate NumFmtId and add new NumFmt
  214. xNumFmt := styles.newNumFmt(cell.NumFmt)
  215. style := cell.style
  216. if style != nil {
  217. XfId = handleStyleForXLSX(style, xNumFmt.NumFmtId, styles)
  218. } else if len(cell.NumFmt) > 0 && s.Cols[c].numFmt != cell.NumFmt {
  219. XfId = handleNumFmtIdForXLSX(xNumFmt.NumFmtId, styles)
  220. }
  221. if c > maxCell {
  222. maxCell = c
  223. }
  224. xC := xlsxC{}
  225. xC.R = fmt.Sprintf("%s%d", numericToLetters(c), r+1)
  226. switch cell.cellType {
  227. case CellTypeString:
  228. if len(cell.Value) > 0 {
  229. xC.V = strconv.Itoa(refTable.AddString(cell.Value))
  230. }
  231. xC.T = "s"
  232. xC.S = XfId
  233. case CellTypeBool:
  234. xC.V = cell.Value
  235. xC.T = "b"
  236. xC.S = XfId
  237. case CellTypeNumeric:
  238. xC.V = cell.Value
  239. xC.S = XfId
  240. case CellTypeDate:
  241. xC.V = cell.Value
  242. xC.S = XfId
  243. case CellTypeFormula:
  244. xC.V = cell.Value
  245. xC.F = &xlsxF{Content: cell.formula}
  246. xC.S = XfId
  247. case CellTypeError:
  248. xC.V = cell.Value
  249. xC.F = &xlsxF{Content: cell.formula}
  250. xC.T = "e"
  251. xC.S = XfId
  252. case CellTypeGeneral:
  253. xC.V = cell.Value
  254. xC.S = XfId
  255. }
  256. xRow.C = append(xRow.C, xC)
  257. if cell.HMerge > 0 || cell.VMerge > 0 {
  258. // r == rownum, c == colnum
  259. mc := xlsxMergeCell{}
  260. start := fmt.Sprintf("%s%d", numericToLetters(c), r+1)
  261. endcol := c + cell.HMerge
  262. endrow := r + cell.VMerge + 1
  263. end := fmt.Sprintf("%s%d", numericToLetters(endcol), endrow)
  264. mc.Ref = start + ":" + end
  265. if worksheet.MergeCells == nil {
  266. worksheet.MergeCells = &xlsxMergeCells{}
  267. }
  268. worksheet.MergeCells.Cells = append(worksheet.MergeCells.Cells, mc)
  269. }
  270. }
  271. xSheet.Row = append(xSheet.Row, xRow)
  272. }
  273. if worksheet.MergeCells != nil {
  274. worksheet.MergeCells.Count = len(worksheet.MergeCells.Cells)
  275. }
  276. worksheet.SheetData = xSheet
  277. dimension := xlsxDimension{}
  278. dimension.Ref = fmt.Sprintf("A1:%s%d",
  279. numericToLetters(maxCell), maxRow+1)
  280. if dimension.Ref == "A1:A1" {
  281. dimension.Ref = "A1"
  282. }
  283. worksheet.Dimension = dimension
  284. return worksheet
  285. }
  286. func handleStyleForXLSX(style *Style, NumFmtId int, styles *xlsxStyleSheet) (XfId int) {
  287. xFont, xFill, xBorder, xCellXf := style.makeXLSXStyleElements()
  288. fontId := styles.addFont(xFont)
  289. fillId := styles.addFill(xFill)
  290. // HACK - adding light grey fill, as in OO and Google
  291. greyfill := xlsxFill{}
  292. greyfill.PatternFill.PatternType = "lightGray"
  293. styles.addFill(greyfill)
  294. borderId := styles.addBorder(xBorder)
  295. xCellXf.FontId = fontId
  296. xCellXf.FillId = fillId
  297. xCellXf.BorderId = borderId
  298. xCellXf.NumFmtId = NumFmtId
  299. // apply the numFmtId when it is not the default cellxf
  300. if xCellXf.NumFmtId > 0 {
  301. xCellXf.ApplyNumberFormat = true
  302. }
  303. xCellXf.Alignment.Horizontal = style.Alignment.Horizontal
  304. xCellXf.Alignment.Indent = style.Alignment.Indent
  305. xCellXf.Alignment.ShrinkToFit = style.Alignment.ShrinkToFit
  306. xCellXf.Alignment.TextRotation = style.Alignment.TextRotation
  307. xCellXf.Alignment.Vertical = style.Alignment.Vertical
  308. xCellXf.Alignment.WrapText = style.Alignment.WrapText
  309. XfId = styles.addCellXf(xCellXf)
  310. return
  311. }
  312. func handleNumFmtIdForXLSX(NumFmtId int, styles *xlsxStyleSheet) (XfId int) {
  313. xCellXf := makeXLSXCellElement()
  314. xCellXf.NumFmtId = NumFmtId
  315. if xCellXf.NumFmtId > 0 {
  316. xCellXf.ApplyNumberFormat = true
  317. }
  318. XfId = styles.addCellXf(xCellXf)
  319. return
  320. }