sheet.go 9.7 KB

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