col.go 13 KB

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