col.go 11 KB

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