col.go 14 KB

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