col.go 12 KB

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