sheet.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. package xlsx
  2. import (
  3. "errors"
  4. "fmt"
  5. "strconv"
  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. Name string
  11. File *File
  12. Rows []*Row
  13. Cols *ColStore
  14. MaxRow int
  15. MaxCol int
  16. Hidden bool
  17. Selected bool
  18. SheetViews []SheetView
  19. SheetFormat SheetFormat
  20. AutoFilter *AutoFilter
  21. DataValidations []*xlsxDataValidation
  22. }
  23. type SheetView struct {
  24. Pane *Pane
  25. }
  26. type Pane struct {
  27. XSplit float64
  28. YSplit float64
  29. TopLeftCell string
  30. ActivePane string
  31. State string // Either "split" or "frozen"
  32. }
  33. type SheetFormat struct {
  34. DefaultColWidth float64
  35. DefaultRowHeight float64
  36. OutlineLevelCol uint8
  37. OutlineLevelRow uint8
  38. }
  39. type AutoFilter struct {
  40. TopLeftCell string
  41. BottomRightCell string
  42. }
  43. // Add a new Row to a Sheet
  44. func (s *Sheet) AddRow() *Row {
  45. row := &Row{Sheet: s}
  46. s.Rows = append(s.Rows, row)
  47. if len(s.Rows) > s.MaxRow {
  48. s.MaxRow = len(s.Rows)
  49. }
  50. return row
  51. }
  52. // Add a new Row to a Sheet at a specific index
  53. func (s *Sheet) AddRowAtIndex(index int) (*Row, error) {
  54. if index < 0 || index > len(s.Rows) {
  55. return nil, errors.New("AddRowAtIndex: index out of bounds")
  56. }
  57. row := &Row{Sheet: s}
  58. s.Rows = append(s.Rows, nil)
  59. if index < len(s.Rows) {
  60. copy(s.Rows[index+1:], s.Rows[index:])
  61. }
  62. s.Rows[index] = row
  63. if len(s.Rows) > s.MaxRow {
  64. s.MaxRow = len(s.Rows)
  65. }
  66. return row, nil
  67. }
  68. // Add a DataValidation to a range of cells
  69. func (s *Sheet) AddDataValidation(dv *xlsxDataValidation) {
  70. s.DataValidations = append(s.DataValidations, dv)
  71. }
  72. // Removes a row at a specific index
  73. func (s *Sheet) RemoveRowAtIndex(index int) error {
  74. if index < 0 || index >= len(s.Rows) {
  75. return errors.New("RemoveRowAtIndex: index out of bounds")
  76. }
  77. s.Rows = append(s.Rows[:index], s.Rows[index+1:]...)
  78. return nil
  79. }
  80. // Make sure we always have as many Rows as we do cells.
  81. func (s *Sheet) maybeAddRow(rowCount int) {
  82. if rowCount > s.MaxRow {
  83. loopCnt := rowCount - s.MaxRow
  84. for i := 0; i < loopCnt; i++ {
  85. row := &Row{Sheet: s}
  86. s.Rows = append(s.Rows, row)
  87. }
  88. s.MaxRow = rowCount
  89. }
  90. }
  91. // Make sure we always have as many Rows as we do cells.
  92. func (s *Sheet) Row(idx int) *Row {
  93. s.maybeAddRow(idx + 1)
  94. return s.Rows[idx]
  95. }
  96. // Return the Col that applies to this Column index, or return nil if no such Col exists
  97. func (s *Sheet) Col(idx int) *Col {
  98. if s.Cols == nil {
  99. panic("trying to use uninitialised ColStore")
  100. }
  101. return s.Cols.FindColByIndex(idx + 1)
  102. }
  103. // Get a Cell by passing it's cartesian coordinates (zero based) as
  104. // row and column integer indexes.
  105. //
  106. // For example:
  107. //
  108. // cell := sheet.Cell(0,0)
  109. //
  110. // ... would set the variable "cell" to contain a Cell struct
  111. // containing the data from the field "A1" on the spreadsheet.
  112. func (sh *Sheet) Cell(row, col int) *Cell {
  113. // If the user requests a row beyond what we have, then extend.
  114. for len(sh.Rows) <= row {
  115. sh.AddRow()
  116. }
  117. r := sh.Rows[row]
  118. for len(r.Cells) <= col {
  119. r.AddCell()
  120. }
  121. return r.Cells[col]
  122. }
  123. //Set the parameters of a column. Parameters are passed as a pointer
  124. //to a Col structure which you much construct yourself.
  125. func (s *Sheet) SetColParameters(col *Col) {
  126. if s.Cols == nil {
  127. panic("trying to use uninitialised ColStore")
  128. }
  129. s.Cols.Add(col)
  130. }
  131. func (s *Sheet) setCol(min, max int, setter func(col *Col)) {
  132. if s.Cols == nil {
  133. panic("trying to use uninitialised ColStore")
  134. }
  135. cols := s.Cols.getOrMakeColsForRange(s.Cols.Root, min, max)
  136. for _, col := range cols {
  137. switch {
  138. case col.Min < min && col.Max > max:
  139. // The column completely envelops the range,
  140. // so we'll split it into three parts and only
  141. // set the width on the part within the range.
  142. // The ColStore will do most of this work for
  143. // us, we just need to create the new Col
  144. // based on the old one.
  145. newCol := col.copyToRange(min, max)
  146. setter(newCol)
  147. s.Cols.Add(newCol)
  148. case col.Min < min:
  149. // If this column crosses the minimum boundary
  150. // of the range we must split it and only
  151. // apply the change within the range. Again,
  152. // we can lean on the ColStore to deal with
  153. // the rest we just need to make the new
  154. // Col.
  155. newCol := col.copyToRange(min, col.Max)
  156. setter(newCol)
  157. s.Cols.Add(newCol)
  158. case col.Max > max:
  159. // Likewise if a col definition crosses the
  160. // maximum boundary of the range, it must also
  161. // be split
  162. newCol := col.copyToRange(col.Min, max)
  163. setter(newCol)
  164. s.Cols.Add(newCol)
  165. default:
  166. newCol := col.copyToRange(min, max)
  167. setter(newCol)
  168. s.Cols.Add(newCol)
  169. }
  170. }
  171. return
  172. }
  173. // Set the width of a range of columns.
  174. func (s *Sheet) SetColWidth(min, max int, width float64) {
  175. s.setCol(min, max, func(col *Col) {
  176. col.SetWidth(width)
  177. })
  178. }
  179. // Set the outline level for a range of columns.
  180. func (s *Sheet) SetOutlineLevel(minCol, maxCol int, outlineLevel uint8) {
  181. s.setCol(minCol, maxCol, func(col *Col) {
  182. col.SetOutlineLevel(outlineLevel)
  183. })
  184. }
  185. // Set the type for a range of columns.
  186. func (s *Sheet) SetType(minCol, maxCol int, cellType CellType) {
  187. s.setCol(minCol, maxCol, func(col *Col) {
  188. col.SetType(cellType)
  189. })
  190. }
  191. // When merging cells, the cell may be the 'original' or the 'covered'.
  192. // First, figure out which cells are merge starting points. Then create
  193. // the necessary cells underlying the merge area.
  194. // Then go through all the underlying cells and apply the appropriate
  195. // border, based on the original cell.
  196. func (s *Sheet) handleMerged() {
  197. merged := make(map[string]*Cell)
  198. for r, row := range s.Rows {
  199. for c, cell := range row.Cells {
  200. if cell.HMerge > 0 || cell.VMerge > 0 {
  201. coord := GetCellIDStringFromCoords(c, r)
  202. merged[coord] = cell
  203. }
  204. }
  205. }
  206. // This loop iterates over all cells that should be merged and applies the correct
  207. // borders to them depending on their position. If any cells required by the merge
  208. // are missing, they will be allocated by s.Cell().
  209. for key, cell := range merged {
  210. maincol, mainrow, _ := GetCoordsFromCellIDString(key)
  211. for rownum := 0; rownum <= cell.VMerge; rownum++ {
  212. for colnum := 0; colnum <= cell.HMerge; colnum++ {
  213. // make cell
  214. s.Cell(mainrow+rownum, maincol+colnum)
  215. }
  216. }
  217. }
  218. }
  219. func (s *Sheet) makeSheetView(worksheet *xlsxWorksheet) {
  220. for index, sheetView := range s.SheetViews {
  221. if sheetView.Pane != nil {
  222. worksheet.SheetViews.SheetView[index].Pane = &xlsxPane{
  223. XSplit: sheetView.Pane.XSplit,
  224. YSplit: sheetView.Pane.YSplit,
  225. TopLeftCell: sheetView.Pane.TopLeftCell,
  226. ActivePane: sheetView.Pane.ActivePane,
  227. State: sheetView.Pane.State,
  228. }
  229. }
  230. }
  231. if s.Selected {
  232. worksheet.SheetViews.SheetView[0].TabSelected = true
  233. }
  234. }
  235. func (s *Sheet) makeSheetFormatPr(worksheet *xlsxWorksheet) {
  236. if s.SheetFormat.DefaultRowHeight != 0 {
  237. worksheet.SheetFormatPr.DefaultRowHeight = s.SheetFormat.DefaultRowHeight
  238. }
  239. worksheet.SheetFormatPr.DefaultColWidth = s.SheetFormat.DefaultColWidth
  240. }
  241. //
  242. func (s *Sheet) makeCols(worksheet *xlsxWorksheet, styles *xlsxStyleSheet) (maxLevelCol uint8) {
  243. maxLevelCol = 0
  244. if s.Cols == nil {
  245. panic("trying to use uninitialised ColStore")
  246. }
  247. s.Cols.ForEach(
  248. func(c int, col *Col) {
  249. XfId := 0
  250. style := col.GetStyle()
  251. hasNumFmt := len(col.numFmt) > 0
  252. if style == nil && hasNumFmt {
  253. style = NewStyle()
  254. }
  255. if hasNumFmt {
  256. xNumFmt := styles.newNumFmt(col.numFmt)
  257. XfId = handleStyleForXLSX(style, xNumFmt.NumFmtId, styles)
  258. }
  259. col.outXfID = XfId
  260. // When the cols content is empty, the cols flag is not output in the xml file.
  261. if worksheet.Cols == nil {
  262. worksheet.Cols = &xlsxCols{Col: []xlsxCol{}}
  263. }
  264. worksheet.Cols.Col = append(worksheet.Cols.Col,
  265. xlsxCol{
  266. Min: col.Min,
  267. Max: col.Max,
  268. Hidden: col.Hidden,
  269. Width: col.Width,
  270. CustomWidth: col.CustomWidth,
  271. Collapsed: col.Collapsed,
  272. OutlineLevel: col.OutlineLevel,
  273. Style: XfId,
  274. BestFit: col.BestFit,
  275. Phonetic: col.Phonetic,
  276. })
  277. if col.OutlineLevel > maxLevelCol {
  278. maxLevelCol = col.OutlineLevel
  279. }
  280. })
  281. return maxLevelCol
  282. }
  283. func (s *Sheet) makeRows(worksheet *xlsxWorksheet, styles *xlsxStyleSheet, refTable *RefTable, maxLevelCol uint8) {
  284. maxRow := 0
  285. maxCell := 0
  286. var maxLevelRow uint8
  287. xSheet := xlsxSheetData{}
  288. for r, row := range s.Rows {
  289. if r > maxRow {
  290. maxRow = r
  291. }
  292. xRow := xlsxRow{}
  293. xRow.R = r + 1
  294. if row.isCustom {
  295. xRow.CustomHeight = true
  296. xRow.Ht = fmt.Sprintf("%g", row.Height)
  297. }
  298. xRow.OutlineLevel = row.OutlineLevel
  299. if row.OutlineLevel > maxLevelRow {
  300. maxLevelRow = row.OutlineLevel
  301. }
  302. for c, cell := range row.Cells {
  303. var XfId int
  304. col := s.Col(c)
  305. if col != nil {
  306. XfId = col.outXfID
  307. }
  308. // generate NumFmtId and add new NumFmt
  309. xNumFmt := styles.newNumFmt(cell.NumFmt)
  310. style := cell.style
  311. switch {
  312. case style != nil:
  313. XfId = handleStyleForXLSX(style, xNumFmt.NumFmtId, styles)
  314. case len(cell.NumFmt) == 0:
  315. // Do nothing
  316. case col == nil:
  317. XfId = handleNumFmtIdForXLSX(xNumFmt.NumFmtId, styles)
  318. case !compareFormatString(col.numFmt, cell.NumFmt):
  319. XfId = handleNumFmtIdForXLSX(xNumFmt.NumFmtId, styles)
  320. }
  321. if c > maxCell {
  322. maxCell = c
  323. }
  324. xC := xlsxC{
  325. S: XfId,
  326. R: GetCellIDStringFromCoords(c, r),
  327. }
  328. if cell.formula != "" {
  329. xC.F = &xlsxF{Content: cell.formula}
  330. }
  331. switch cell.cellType {
  332. case CellTypeInline:
  333. // Inline strings are turned into shared strings since they are more efficient.
  334. // This is what Excel does as well.
  335. fallthrough
  336. case CellTypeString:
  337. if len(cell.Value) > 0 {
  338. xC.V = strconv.Itoa(refTable.AddString(cell.Value))
  339. }
  340. xC.T = "s"
  341. case CellTypeNumeric:
  342. // Numeric is the default, so the type can be left blank
  343. xC.V = cell.Value
  344. case CellTypeBool:
  345. xC.V = cell.Value
  346. xC.T = "b"
  347. case CellTypeError:
  348. xC.V = cell.Value
  349. xC.T = "e"
  350. case CellTypeDate:
  351. xC.V = cell.Value
  352. xC.T = "d"
  353. case CellTypeStringFormula:
  354. xC.V = cell.Value
  355. xC.T = "str"
  356. default:
  357. panic(errors.New("unknown cell type cannot be marshaled"))
  358. }
  359. xRow.C = append(xRow.C, xC)
  360. if nil != cell.DataValidation {
  361. if nil == worksheet.DataValidations {
  362. worksheet.DataValidations = &xlsxDataValidations{}
  363. }
  364. cell.DataValidation.Sqref = xC.R
  365. worksheet.DataValidations.DataValidation = append(worksheet.DataValidations.DataValidation, cell.DataValidation)
  366. worksheet.DataValidations.Count = len(worksheet.DataValidations.DataValidation)
  367. }
  368. if cell.HMerge > 0 || cell.VMerge > 0 {
  369. // r == rownum, c == colnum
  370. mc := xlsxMergeCell{}
  371. start := GetCellIDStringFromCoords(c, r)
  372. endCol := c + cell.HMerge
  373. endRow := r + cell.VMerge
  374. end := GetCellIDStringFromCoords(endCol, endRow)
  375. mc.Ref = start + cellRangeChar + end
  376. if worksheet.MergeCells == nil {
  377. worksheet.MergeCells = &xlsxMergeCells{}
  378. }
  379. worksheet.MergeCells.Cells = append(worksheet.MergeCells.Cells, mc)
  380. }
  381. }
  382. xSheet.Row = append(xSheet.Row, xRow)
  383. }
  384. // Update sheet format with the freshly determined max levels
  385. s.SheetFormat.OutlineLevelCol = maxLevelCol
  386. s.SheetFormat.OutlineLevelRow = maxLevelRow
  387. // .. and then also apply this to the xml worksheet
  388. worksheet.SheetFormatPr.OutlineLevelCol = s.SheetFormat.OutlineLevelCol
  389. worksheet.SheetFormatPr.OutlineLevelRow = s.SheetFormat.OutlineLevelRow
  390. if worksheet.MergeCells != nil {
  391. worksheet.MergeCells.Count = len(worksheet.MergeCells.Cells)
  392. }
  393. if s.AutoFilter != nil {
  394. worksheet.AutoFilter = &xlsxAutoFilter{Ref: fmt.Sprintf("%v:%v", s.AutoFilter.TopLeftCell, s.AutoFilter.BottomRightCell)}
  395. }
  396. worksheet.SheetData = xSheet
  397. dimension := xlsxDimension{}
  398. dimension.Ref = "A1:" + GetCellIDStringFromCoords(maxCell, maxRow)
  399. if dimension.Ref == "A1:A1" {
  400. dimension.Ref = "A1"
  401. }
  402. worksheet.Dimension = dimension
  403. }
  404. func (s *Sheet) makeDataValidations(worksheet *xlsxWorksheet) {
  405. if len(s.DataValidations) > 0 {
  406. if worksheet.DataValidations == nil {
  407. worksheet.DataValidations = &xlsxDataValidations{}
  408. }
  409. for _, dv := range s.DataValidations {
  410. worksheet.DataValidations.DataValidation = append(worksheet.DataValidations.DataValidation, dv)
  411. }
  412. worksheet.DataValidations.Count = len(worksheet.DataValidations.DataValidation)
  413. }
  414. }
  415. // Dump sheet to its XML representation, intended for internal use only
  416. func (s *Sheet) makeXLSXSheet(refTable *RefTable, styles *xlsxStyleSheet) *xlsxWorksheet {
  417. worksheet := newXlsxWorksheet()
  418. // Scan through the sheet and see if there are any merged cells. If there
  419. // are, we may need to extend the size of the sheet. There needs to be
  420. // phantom cells underlying the area covered by the merged cell
  421. s.handleMerged()
  422. s.makeSheetView(worksheet)
  423. s.makeSheetFormatPr(worksheet)
  424. maxLevelCol := s.makeCols(worksheet, styles)
  425. s.makeDataValidations(worksheet)
  426. s.makeRows(worksheet, styles, refTable, maxLevelCol)
  427. return worksheet
  428. }
  429. func handleStyleForXLSX(style *Style, NumFmtId int, styles *xlsxStyleSheet) (XfId int) {
  430. xFont, xFill, xBorder, xCellXf := style.makeXLSXStyleElements()
  431. fontId := styles.addFont(xFont)
  432. fillId := styles.addFill(xFill)
  433. // HACK - adding light grey fill, as in OO and Google
  434. greyfill := xlsxFill{}
  435. greyfill.PatternFill.PatternType = "lightGray"
  436. styles.addFill(greyfill)
  437. borderId := styles.addBorder(xBorder)
  438. xCellXf.FontId = fontId
  439. xCellXf.FillId = fillId
  440. xCellXf.BorderId = borderId
  441. xCellXf.NumFmtId = NumFmtId
  442. // apply the numFmtId when it is not the default cellxf
  443. if xCellXf.NumFmtId > 0 {
  444. xCellXf.ApplyNumberFormat = true
  445. }
  446. xCellXf.Alignment.Horizontal = style.Alignment.Horizontal
  447. xCellXf.Alignment.Indent = style.Alignment.Indent
  448. xCellXf.Alignment.ShrinkToFit = style.Alignment.ShrinkToFit
  449. xCellXf.Alignment.TextRotation = style.Alignment.TextRotation
  450. xCellXf.Alignment.Vertical = style.Alignment.Vertical
  451. xCellXf.Alignment.WrapText = style.Alignment.WrapText
  452. XfId = styles.addCellXf(xCellXf)
  453. return
  454. }
  455. func handleNumFmtIdForXLSX(NumFmtId int, styles *xlsxStyleSheet) (XfId int) {
  456. xCellXf := makeXLSXCellElement()
  457. xCellXf.NumFmtId = NumFmtId
  458. if xCellXf.NumFmtId > 0 {
  459. xCellXf.ApplyNumberFormat = true
  460. }
  461. XfId = styles.addCellXf(xCellXf)
  462. return
  463. }