sheet.go 12 KB

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