col.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. // Copyright 2016 - 2019 The excelize Authors. All rights reserved. Use of
  2. // this source code is governed by a BSD-style license that can be found in
  3. // the LICENSE file.
  4. //
  5. // Package excelize providing a set of functions that allow you to write to
  6. // and read from XLSX files. Support reads and writes XLSX file generated by
  7. // Microsoft Excel™ 2007 and later. Support save file without losing original
  8. // charts of XLSX. This library needs Go version 1.8 or later.
  9. package excelize
  10. import (
  11. "math"
  12. )
  13. // Define the default cell size and EMU unit of measurement.
  14. const (
  15. defaultColWidthPixels float64 = 64
  16. defaultRowHeightPixels float64 = 20
  17. EMU int = 9525
  18. )
  19. // GetColVisible provides a function to get visible of a single column by given
  20. // worksheet name and column name. For example, get visible state of column D
  21. // in Sheet1:
  22. //
  23. // xlsx.GetColVisible("Sheet1", "D")
  24. //
  25. func (f *File) GetColVisible(sheet, col string) bool {
  26. colNum := MustColumnNameToNumber(col)
  27. xlsx := f.workSheetReader(sheet)
  28. if xlsx.Cols == nil {
  29. return true
  30. }
  31. visible := true
  32. for c := range xlsx.Cols.Col {
  33. colData := &xlsx.Cols.Col[c]
  34. if colData.Min <= colNum && colNum <= colData.Max {
  35. visible = !colData.Hidden
  36. }
  37. }
  38. return visible
  39. }
  40. // SetColVisible provides a function to set visible of a single column by given
  41. // worksheet name and column name. For example, hide column D in Sheet1:
  42. //
  43. // xlsx.SetColVisible("Sheet1", "D", false)
  44. //
  45. func (f *File) SetColVisible(sheet, col string, visible bool) {
  46. colNum := MustColumnNameToNumber(col)
  47. colData := xlsxCol{
  48. Min: colNum,
  49. Max: colNum,
  50. Hidden: !visible,
  51. CustomWidth: true,
  52. }
  53. xlsx := f.workSheetReader(sheet)
  54. if xlsx.Cols == nil {
  55. cols := xlsxCols{}
  56. cols.Col = append(cols.Col, colData)
  57. xlsx.Cols = &cols
  58. return
  59. }
  60. for v := range xlsx.Cols.Col {
  61. if xlsx.Cols.Col[v].Min <= colNum && colNum <= xlsx.Cols.Col[v].Max {
  62. colData = xlsx.Cols.Col[v]
  63. }
  64. }
  65. colData.Min = colNum
  66. colData.Max = colNum
  67. colData.Hidden = !visible
  68. colData.CustomWidth = true
  69. xlsx.Cols.Col = append(xlsx.Cols.Col, colData)
  70. }
  71. // GetColOutlineLevel provides a function to get outline level of a single
  72. // column by given worksheet name and column name. For example, get outline
  73. // level of column D in Sheet1:
  74. //
  75. // xlsx.GetColOutlineLevel("Sheet1", "D")
  76. //
  77. func (f *File) GetColOutlineLevel(sheet, col string) uint8 {
  78. colNum := MustColumnNameToNumber(col)
  79. xlsx := f.workSheetReader(sheet)
  80. level := uint8(0)
  81. if xlsx.Cols == nil {
  82. return level
  83. }
  84. for c := range xlsx.Cols.Col {
  85. colData := &xlsx.Cols.Col[c]
  86. if colData.Min <= colNum && colNum <= colData.Max {
  87. level = colData.OutlineLevel
  88. }
  89. }
  90. return level
  91. }
  92. // SetColOutlineLevel provides a function to set outline level of a single
  93. // column by given worksheet name and column name. For example, set outline
  94. // level of column D in Sheet1 to 2:
  95. //
  96. // xlsx.SetColOutlineLevel("Sheet1", "D", 2)
  97. //
  98. func (f *File) SetColOutlineLevel(sheet, col string, level uint8) {
  99. colNum := MustColumnNameToNumber(col)
  100. colData := xlsxCol{
  101. Min: colNum,
  102. Max: colNum,
  103. OutlineLevel: level,
  104. CustomWidth: true,
  105. }
  106. xlsx := f.workSheetReader(sheet)
  107. if xlsx.Cols == nil {
  108. cols := xlsxCols{}
  109. cols.Col = append(cols.Col, colData)
  110. xlsx.Cols = &cols
  111. return
  112. }
  113. for v := range xlsx.Cols.Col {
  114. if xlsx.Cols.Col[v].Min <= colNum && colNum <= xlsx.Cols.Col[v].Max {
  115. colData = xlsx.Cols.Col[v]
  116. }
  117. }
  118. colData.Min = colNum
  119. colData.Max = colNum
  120. colData.OutlineLevel = level
  121. colData.CustomWidth = true
  122. xlsx.Cols.Col = append(xlsx.Cols.Col, colData)
  123. }
  124. // SetColWidth provides a function to set the width of a single column or
  125. // multiple columns. For example:
  126. //
  127. // xlsx := excelize.NewFile()
  128. // xlsx.SetColWidth("Sheet1", "A", "H", 20)
  129. // err := xlsx.Save()
  130. // if err != nil {
  131. // fmt.Println(err)
  132. // }
  133. //
  134. func (f *File) SetColWidth(sheet, startcol, endcol string, width float64) {
  135. min := MustColumnNameToNumber(startcol)
  136. max := MustColumnNameToNumber(endcol)
  137. if min > max {
  138. min, max = max, min
  139. }
  140. xlsx := f.workSheetReader(sheet)
  141. col := xlsxCol{
  142. Min: min,
  143. Max: max,
  144. Width: width,
  145. CustomWidth: true,
  146. }
  147. if xlsx.Cols != nil {
  148. xlsx.Cols.Col = append(xlsx.Cols.Col, col)
  149. } else {
  150. cols := xlsxCols{}
  151. cols.Col = append(cols.Col, col)
  152. xlsx.Cols = &cols
  153. }
  154. }
  155. // positionObjectPixels calculate the vertices that define the position of a
  156. // graphical object within the worksheet in pixels.
  157. //
  158. // +------------+------------+
  159. // | A | B |
  160. // +-----+------------+------------+
  161. // | |(x1,y1) | |
  162. // | 1 |(A1)._______|______ |
  163. // | | | | |
  164. // | | | | |
  165. // +-----+----| OBJECT |-----+
  166. // | | | | |
  167. // | 2 | |______________. |
  168. // | | | (B2)|
  169. // | | | (x2,y2)|
  170. // +-----+------------+------------+
  171. //
  172. // Example of an object that covers some of the area from cell A1 to B2.
  173. //
  174. // Based on the width and height of the object we need to calculate 8 vars:
  175. //
  176. // colStart, rowStart, colEnd, rowEnd, x1, y1, x2, y2.
  177. //
  178. // We also calculate the absolute x and y position of the top left vertex of
  179. // the object. This is required for images.
  180. //
  181. // The width and height of the cells that the object occupies can be
  182. // variable and have to be taken into account.
  183. //
  184. // The values of col_start and row_start are passed in from the calling
  185. // function. The values of col_end and row_end are calculated by
  186. // subtracting the width and height of the object from the width and
  187. // height of the underlying cells.
  188. //
  189. // colStart # Col containing upper left corner of object.
  190. // x1 # Distance to left side of object.
  191. //
  192. // rowStart # Row containing top left corner of object.
  193. // y1 # Distance to top of object.
  194. //
  195. // colEnd # Col containing lower right corner of object.
  196. // x2 # Distance to right side of object.
  197. //
  198. // rowEnd # Row containing bottom right corner of object.
  199. // y2 # Distance to bottom of object.
  200. //
  201. // width # Width of object frame.
  202. // height # Height of object frame.
  203. //
  204. // xAbs # Absolute distance to left side of object.
  205. // yAbs # Absolute distance to top side of object.
  206. //
  207. func (f *File) positionObjectPixels(sheet string, col, row, x1, y1, width, height int) (int, int, int, int, int, int, int, int) {
  208. xAbs := 0
  209. yAbs := 0
  210. // Calculate the absolute x offset of the top-left vertex.
  211. for colID := 1; colID <= col; colID++ {
  212. xAbs += f.getColWidth(sheet, colID)
  213. }
  214. xAbs += x1
  215. // Calculate the absolute y offset of the top-left vertex.
  216. // Store the column change to allow optimisations.
  217. for rowID := 1; rowID <= row; rowID++ {
  218. yAbs += f.getRowHeight(sheet, rowID)
  219. }
  220. yAbs += y1
  221. // Adjust start column for offsets that are greater than the col width.
  222. for x1 >= f.getColWidth(sheet, col) {
  223. x1 -= f.getColWidth(sheet, col)
  224. col++
  225. }
  226. // Adjust start row for offsets that are greater than the row height.
  227. for y1 >= f.getRowHeight(sheet, row) {
  228. y1 -= f.getRowHeight(sheet, row)
  229. row++
  230. }
  231. // Initialise end cell to the same as the start cell.
  232. colEnd := col
  233. rowEnd := row
  234. width += x1
  235. height += y1
  236. // Subtract the underlying cell widths to find end cell of the object.
  237. for width >= f.getColWidth(sheet, colEnd) {
  238. colEnd++
  239. width -= f.getColWidth(sheet, colEnd)
  240. }
  241. // Subtract the underlying cell heights to find end cell of the object.
  242. for height >= f.getRowHeight(sheet, rowEnd) {
  243. rowEnd++
  244. height -= f.getRowHeight(sheet, rowEnd)
  245. }
  246. // The end vertices are whatever is left from the width and height.
  247. x2 := width
  248. y2 := height
  249. return col, row, xAbs, yAbs, colEnd, rowEnd, x2, y2
  250. }
  251. // getColWidth provides a function to get column width in pixels by given
  252. // sheet name and column index.
  253. func (f *File) getColWidth(sheet string, col int) int {
  254. xlsx := f.workSheetReader(sheet)
  255. if xlsx.Cols != nil {
  256. var width float64
  257. for _, v := range xlsx.Cols.Col {
  258. if v.Min <= col && col <= v.Max {
  259. width = v.Width
  260. }
  261. }
  262. if width != 0 {
  263. return int(convertColWidthToPixels(width))
  264. }
  265. }
  266. // Optimisation for when the column widths haven't changed.
  267. return int(defaultColWidthPixels)
  268. }
  269. // GetColWidth provides a function to get column width by given worksheet name
  270. // and column index.
  271. func (f *File) GetColWidth(sheet, col string) float64 {
  272. colNum := MustColumnNameToNumber(col)
  273. xlsx := f.workSheetReader(sheet)
  274. if xlsx.Cols != nil {
  275. var width float64
  276. for _, v := range xlsx.Cols.Col {
  277. if v.Min <= colNum && colNum <= v.Max {
  278. width = v.Width
  279. }
  280. }
  281. if width != 0 {
  282. return width
  283. }
  284. }
  285. // Optimisation for when the column widths haven't changed.
  286. return defaultColWidthPixels
  287. }
  288. // InsertCol provides a function to insert a new column before given column
  289. // index. For example, create a new column before column C in Sheet1:
  290. //
  291. // xlsx.InsertCol("Sheet1", "C")
  292. //
  293. func (f *File) InsertCol(sheet, col string) {
  294. num, err := ColumnNameToNumber(col)
  295. if err != nil {
  296. panic(err)
  297. }
  298. f.adjustHelper(sheet, columns, num, 1)
  299. }
  300. // RemoveCol provides a function to remove single column by given worksheet
  301. // name and column index. For example, remove column C in Sheet1:
  302. //
  303. // xlsx.RemoveCol("Sheet1", "C")
  304. //
  305. // Use this method with caution, which will affect changes in references such
  306. // as formulas, charts, and so on. If there is any referenced value of the
  307. // worksheet, it will cause a file error when you open it. The excelize only
  308. // partially updates these references currently.
  309. func (f *File) RemoveCol(sheet, col string) {
  310. num, err := ColumnNameToNumber(col)
  311. if err != nil {
  312. panic(err) // Fail fast to avoid possible future side effects!
  313. }
  314. xlsx := f.workSheetReader(sheet)
  315. for rowIdx := range xlsx.SheetData.Row {
  316. rowData := xlsx.SheetData.Row[rowIdx]
  317. for colIdx, cellData := range rowData.C {
  318. colName, _, _ := SplitCellName(cellData.R)
  319. if colName == col {
  320. rowData.C = append(rowData.C[:colIdx], rowData.C[colIdx+1:]...)
  321. }
  322. }
  323. }
  324. f.adjustHelper(sheet, columns, num, -1)
  325. }
  326. // convertColWidthToPixels provieds function to convert the width of a cell
  327. // from user's units to pixels. Excel rounds the column width to the nearest
  328. // pixel. If the width hasn't been set by the user we use the default value.
  329. // If the column is hidden it has a value of zero.
  330. func convertColWidthToPixels(width float64) float64 {
  331. var padding float64 = 5
  332. var pixels float64
  333. var maxDigitWidth float64 = 7
  334. if width == 0 {
  335. return pixels
  336. }
  337. if width < 1 {
  338. pixels = (width * 12) + 0.5
  339. return math.Ceil(pixels)
  340. }
  341. pixels = (width*maxDigitWidth + 0.5) + padding
  342. return math.Ceil(pixels)
  343. }