col.go 11 KB

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