sheet.go 10 KB

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