col.go 13 KB

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