sheet.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  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. // if nil != col.DataValidation {
  281. // if nil == worksheet.DataValidations {
  282. // worksheet.DataValidations = &xlsxDataValidations{}
  283. // }
  284. // colName := ColIndexToLetters(c)
  285. // for _, dd := range col.DataValidation {
  286. // if dd.minRow == dd.maxRow {
  287. // dd.Sqref = colName + RowIndexToString(dd.minRow)
  288. // } else {
  289. // dd.Sqref = colName + RowIndexToString(dd.minRow) + cellRangeChar + colName + RowIndexToString(dd.maxRow)
  290. // }
  291. })
  292. return maxLevelCol
  293. }
  294. func (s *Sheet) makeRows(worksheet *xlsxWorksheet, styles *xlsxStyleSheet, refTable *RefTable, maxLevelCol uint8) {
  295. maxRow := 0
  296. maxCell := 0
  297. var maxLevelRow uint8
  298. xSheet := xlsxSheetData{}
  299. for r, row := range s.Rows {
  300. if r > maxRow {
  301. maxRow = r
  302. }
  303. xRow := xlsxRow{}
  304. xRow.R = r + 1
  305. if row.isCustom {
  306. xRow.CustomHeight = true
  307. xRow.Ht = fmt.Sprintf("%g", row.Height)
  308. }
  309. xRow.OutlineLevel = row.OutlineLevel
  310. if row.OutlineLevel > maxLevelRow {
  311. maxLevelRow = row.OutlineLevel
  312. }
  313. for c, cell := range row.Cells {
  314. var XfId int
  315. col := s.Col(c)
  316. if col != nil {
  317. XfId = col.outXfID
  318. }
  319. // generate NumFmtId and add new NumFmt
  320. xNumFmt := styles.newNumFmt(cell.NumFmt)
  321. style := cell.style
  322. switch {
  323. case style != nil:
  324. XfId = handleStyleForXLSX(style, xNumFmt.NumFmtId, styles)
  325. case len(cell.NumFmt) == 0:
  326. // Do nothing
  327. case col == nil:
  328. XfId = handleNumFmtIdForXLSX(xNumFmt.NumFmtId, styles)
  329. case !compareFormatString(col.numFmt, cell.NumFmt):
  330. XfId = handleNumFmtIdForXLSX(xNumFmt.NumFmtId, styles)
  331. }
  332. if c > maxCell {
  333. maxCell = c
  334. }
  335. xC := xlsxC{
  336. S: XfId,
  337. R: GetCellIDStringFromCoords(c, r),
  338. }
  339. if cell.formula != "" {
  340. xC.F = &xlsxF{Content: cell.formula}
  341. }
  342. switch cell.cellType {
  343. case CellTypeInline:
  344. // Inline strings are turned into shared strings since they are more efficient.
  345. // This is what Excel does as well.
  346. fallthrough
  347. case CellTypeString:
  348. if len(cell.Value) > 0 {
  349. xC.V = strconv.Itoa(refTable.AddString(cell.Value))
  350. }
  351. xC.T = "s"
  352. case CellTypeNumeric:
  353. // Numeric is the default, so the type can be left blank
  354. xC.V = cell.Value
  355. case CellTypeBool:
  356. xC.V = cell.Value
  357. xC.T = "b"
  358. case CellTypeError:
  359. xC.V = cell.Value
  360. xC.T = "e"
  361. case CellTypeDate:
  362. xC.V = cell.Value
  363. xC.T = "d"
  364. case CellTypeStringFormula:
  365. xC.V = cell.Value
  366. xC.T = "str"
  367. default:
  368. panic(errors.New("unknown cell type cannot be marshaled"))
  369. }
  370. xRow.C = append(xRow.C, xC)
  371. if nil != cell.DataValidation {
  372. if nil == worksheet.DataValidations {
  373. worksheet.DataValidations = &xlsxDataValidations{}
  374. }
  375. cell.DataValidation.Sqref = xC.R
  376. worksheet.DataValidations.DataValidation = append(worksheet.DataValidations.DataValidation, cell.DataValidation)
  377. worksheet.DataValidations.Count = len(worksheet.DataValidations.DataValidation)
  378. }
  379. if cell.HMerge > 0 || cell.VMerge > 0 {
  380. // r == rownum, c == colnum
  381. mc := xlsxMergeCell{}
  382. start := GetCellIDStringFromCoords(c, r)
  383. endCol := c + cell.HMerge
  384. endRow := r + cell.VMerge
  385. end := GetCellIDStringFromCoords(endCol, endRow)
  386. mc.Ref = start + cellRangeChar + end
  387. if worksheet.MergeCells == nil {
  388. worksheet.MergeCells = &xlsxMergeCells{}
  389. }
  390. worksheet.MergeCells.Cells = append(worksheet.MergeCells.Cells, mc)
  391. }
  392. }
  393. xSheet.Row = append(xSheet.Row, xRow)
  394. }
  395. // Update sheet format with the freshly determined max levels
  396. s.SheetFormat.OutlineLevelCol = maxLevelCol
  397. s.SheetFormat.OutlineLevelRow = maxLevelRow
  398. // .. and then also apply this to the xml worksheet
  399. worksheet.SheetFormatPr.OutlineLevelCol = s.SheetFormat.OutlineLevelCol
  400. worksheet.SheetFormatPr.OutlineLevelRow = s.SheetFormat.OutlineLevelRow
  401. if worksheet.MergeCells != nil {
  402. worksheet.MergeCells.Count = len(worksheet.MergeCells.Cells)
  403. }
  404. if s.AutoFilter != nil {
  405. worksheet.AutoFilter = &xlsxAutoFilter{Ref: fmt.Sprintf("%v:%v", s.AutoFilter.TopLeftCell, s.AutoFilter.BottomRightCell)}
  406. }
  407. worksheet.SheetData = xSheet
  408. dimension := xlsxDimension{}
  409. dimension.Ref = "A1:" + GetCellIDStringFromCoords(maxCell, maxRow)
  410. if dimension.Ref == "A1:A1" {
  411. dimension.Ref = "A1"
  412. }
  413. worksheet.Dimension = dimension
  414. }
  415. func (s *Sheet) makeDataValidations(worksheet *xlsxWorksheet) {
  416. if len(s.DataValidations) > 0 {
  417. if worksheet.DataValidations == nil {
  418. worksheet.DataValidations = &xlsxDataValidations{}
  419. }
  420. for _, dv := range s.DataValidations {
  421. worksheet.DataValidations.DataValidation = append(worksheet.DataValidations.DataValidation, dv)
  422. }
  423. worksheet.DataValidations.Count = len(worksheet.DataValidations.DataValidation)
  424. }
  425. }
  426. // Dump sheet to its XML representation, intended for internal use only
  427. func (s *Sheet) makeXLSXSheet(refTable *RefTable, styles *xlsxStyleSheet) *xlsxWorksheet {
  428. worksheet := newXlsxWorksheet()
  429. // Scan through the sheet and see if there are any merged cells. If there
  430. // are, we may need to extend the size of the sheet. There needs to be
  431. // phantom cells underlying the area covered by the merged cell
  432. s.handleMerged()
  433. s.makeSheetView(worksheet)
  434. s.makeSheetFormatPr(worksheet)
  435. maxLevelCol := s.makeCols(worksheet, styles)
  436. s.makeDataValidations(worksheet)
  437. s.makeRows(worksheet, styles, refTable, maxLevelCol)
  438. return worksheet
  439. }
  440. func handleStyleForXLSX(style *Style, NumFmtId int, styles *xlsxStyleSheet) (XfId int) {
  441. xFont, xFill, xBorder, xCellXf := style.makeXLSXStyleElements()
  442. fontId := styles.addFont(xFont)
  443. fillId := styles.addFill(xFill)
  444. // HACK - adding light grey fill, as in OO and Google
  445. greyfill := xlsxFill{}
  446. greyfill.PatternFill.PatternType = "lightGray"
  447. styles.addFill(greyfill)
  448. borderId := styles.addBorder(xBorder)
  449. xCellXf.FontId = fontId
  450. xCellXf.FillId = fillId
  451. xCellXf.BorderId = borderId
  452. xCellXf.NumFmtId = NumFmtId
  453. // apply the numFmtId when it is not the default cellxf
  454. if xCellXf.NumFmtId > 0 {
  455. xCellXf.ApplyNumberFormat = true
  456. }
  457. xCellXf.Alignment.Horizontal = style.Alignment.Horizontal
  458. xCellXf.Alignment.Indent = style.Alignment.Indent
  459. xCellXf.Alignment.ShrinkToFit = style.Alignment.ShrinkToFit
  460. xCellXf.Alignment.TextRotation = style.Alignment.TextRotation
  461. xCellXf.Alignment.Vertical = style.Alignment.Vertical
  462. xCellXf.Alignment.WrapText = style.Alignment.WrapText
  463. XfId = styles.addCellXf(xCellXf)
  464. return
  465. }
  466. func handleNumFmtIdForXLSX(NumFmtId int, styles *xlsxStyleSheet) (XfId int) {
  467. xCellXf := makeXLSXCellElement()
  468. xCellXf.NumFmtId = NumFmtId
  469. if xCellXf.NumFmtId > 0 {
  470. xCellXf.ApplyNumberFormat = true
  471. }
  472. XfId = styles.addCellXf(xCellXf)
  473. return
  474. }