col.go 11 KB

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