sheet.go 10 KB

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