sheet.go 11 KB

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