col.go 11 KB

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