sheet.go 11 KB

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