sheet.go 11 KB

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