sheet.go 12 KB

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