sheet.go 9.7 KB

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