sheet.go 11 KB

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