col.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776
  1. // Copyright 2016 - 2023 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 and
  6. // read from XLAM / XLSM / XLSX / XLTM / XLTX files. Supports reading and
  7. // writing spreadsheet documents generated by Microsoft Excel™ 2007 and later.
  8. // Supports complex components by high compatibility, and provided streaming
  9. // API for generating or reading data from a worksheet with huge amounts of
  10. // data. This library needs Go version 1.16 or later.
  11. package excelize
  12. import (
  13. "bytes"
  14. "encoding/xml"
  15. "math"
  16. "strconv"
  17. "strings"
  18. "github.com/mohae/deepcopy"
  19. )
  20. // Define the default cell size and EMU unit of measurement.
  21. const (
  22. defaultColWidth float64 = 9.140625
  23. defaultColWidthPixels float64 = 64
  24. defaultRowHeight float64 = 15
  25. defaultRowHeightPixels float64 = 20
  26. EMU int = 9525
  27. )
  28. // Cols defines an iterator to a sheet
  29. type Cols struct {
  30. err error
  31. curCol, totalCols, totalRows, stashCol int
  32. rawCellValue bool
  33. sheet string
  34. f *File
  35. sheetXML []byte
  36. sst *xlsxSST
  37. }
  38. // GetCols gets the value of all cells by columns on the worksheet based on the
  39. // given worksheet name, returned as a two-dimensional array, where the value
  40. // of the cell is converted to the `string` type. If the cell format can be
  41. // applied to the value of the cell, the applied value will be used, otherwise
  42. // the original value will be used.
  43. //
  44. // For example, get and traverse the value of all cells by columns on a
  45. // worksheet named
  46. // 'Sheet1':
  47. //
  48. // cols, err := f.GetCols("Sheet1")
  49. // if err != nil {
  50. // fmt.Println(err)
  51. // return
  52. // }
  53. // for _, col := range cols {
  54. // for _, rowCell := range col {
  55. // fmt.Print(rowCell, "\t")
  56. // }
  57. // fmt.Println()
  58. // }
  59. func (f *File) GetCols(sheet string, opts ...Options) ([][]string, error) {
  60. cols, err := f.Cols(sheet)
  61. if err != nil {
  62. return nil, err
  63. }
  64. results := make([][]string, 0, 64)
  65. for cols.Next() {
  66. col, _ := cols.Rows(opts...)
  67. results = append(results, col)
  68. }
  69. return results, nil
  70. }
  71. // Next will return true if the next column is found.
  72. func (cols *Cols) Next() bool {
  73. cols.curCol++
  74. return cols.curCol <= cols.totalCols
  75. }
  76. // Error will return an error when the error occurs.
  77. func (cols *Cols) Error() error {
  78. return cols.err
  79. }
  80. // Rows return the current column's row values.
  81. func (cols *Cols) Rows(opts ...Options) ([]string, error) {
  82. var rowIterator rowXMLIterator
  83. if cols.stashCol >= cols.curCol {
  84. return rowIterator.cells, rowIterator.err
  85. }
  86. cols.rawCellValue = getOptions(opts...).RawCellValue
  87. if cols.sst, rowIterator.err = cols.f.sharedStringsReader(); rowIterator.err != nil {
  88. return rowIterator.cells, rowIterator.err
  89. }
  90. decoder := cols.f.xmlNewDecoder(bytes.NewReader(cols.sheetXML))
  91. for {
  92. token, _ := decoder.Token()
  93. if token == nil {
  94. break
  95. }
  96. switch xmlElement := token.(type) {
  97. case xml.StartElement:
  98. rowIterator.inElement = xmlElement.Name.Local
  99. if rowIterator.inElement == "row" {
  100. rowIterator.cellCol = 0
  101. rowIterator.cellRow++
  102. attrR, _ := attrValToInt("r", xmlElement.Attr)
  103. if attrR != 0 {
  104. rowIterator.cellRow = attrR
  105. }
  106. }
  107. if cols.rowXMLHandler(&rowIterator, &xmlElement, decoder); rowIterator.err != nil {
  108. return rowIterator.cells, rowIterator.err
  109. }
  110. case xml.EndElement:
  111. if xmlElement.Name.Local == "sheetData" {
  112. return rowIterator.cells, rowIterator.err
  113. }
  114. }
  115. }
  116. return rowIterator.cells, rowIterator.err
  117. }
  118. // columnXMLIterator defined runtime use field for the worksheet column SAX parser.
  119. type columnXMLIterator struct {
  120. err error
  121. cols Cols
  122. cellCol, curRow, row int
  123. }
  124. // columnXMLHandler parse the column XML element of the worksheet.
  125. func columnXMLHandler(colIterator *columnXMLIterator, xmlElement *xml.StartElement) {
  126. colIterator.err = nil
  127. inElement := xmlElement.Name.Local
  128. if inElement == "row" {
  129. colIterator.row++
  130. for _, attr := range xmlElement.Attr {
  131. if attr.Name.Local == "r" {
  132. if colIterator.curRow, colIterator.err = strconv.Atoi(attr.Value); colIterator.err != nil {
  133. return
  134. }
  135. colIterator.row = colIterator.curRow
  136. }
  137. }
  138. colIterator.cols.totalRows = colIterator.row
  139. colIterator.cellCol = 0
  140. }
  141. if inElement == "c" {
  142. colIterator.cellCol++
  143. for _, attr := range xmlElement.Attr {
  144. if attr.Name.Local == "r" {
  145. if colIterator.cellCol, _, colIterator.err = CellNameToCoordinates(attr.Value); colIterator.err != nil {
  146. return
  147. }
  148. }
  149. }
  150. if colIterator.cellCol > colIterator.cols.totalCols {
  151. colIterator.cols.totalCols = colIterator.cellCol
  152. }
  153. }
  154. }
  155. // rowXMLHandler parse the row XML element of the worksheet.
  156. func (cols *Cols) rowXMLHandler(rowIterator *rowXMLIterator, xmlElement *xml.StartElement, decoder *xml.Decoder) {
  157. if rowIterator.inElement == "c" {
  158. rowIterator.cellCol++
  159. for _, attr := range xmlElement.Attr {
  160. if attr.Name.Local == "r" {
  161. if rowIterator.cellCol, rowIterator.cellRow, rowIterator.err = CellNameToCoordinates(attr.Value); rowIterator.err != nil {
  162. return
  163. }
  164. }
  165. }
  166. blank := rowIterator.cellRow - len(rowIterator.cells)
  167. for i := 1; i < blank; i++ {
  168. rowIterator.cells = append(rowIterator.cells, "")
  169. }
  170. if rowIterator.cellCol == cols.curCol {
  171. colCell := xlsxC{}
  172. _ = decoder.DecodeElement(&colCell, xmlElement)
  173. val, _ := colCell.getValueFrom(cols.f, cols.sst, cols.rawCellValue)
  174. rowIterator.cells = append(rowIterator.cells, val)
  175. }
  176. }
  177. }
  178. // Cols returns a columns iterator, used for streaming reading data for a
  179. // worksheet with a large data. This function is concurrency safe. For
  180. // example:
  181. //
  182. // cols, err := f.Cols("Sheet1")
  183. // if err != nil {
  184. // fmt.Println(err)
  185. // return
  186. // }
  187. // for cols.Next() {
  188. // col, err := cols.Rows()
  189. // if err != nil {
  190. // fmt.Println(err)
  191. // }
  192. // for _, rowCell := range col {
  193. // fmt.Print(rowCell, "\t")
  194. // }
  195. // fmt.Println()
  196. // }
  197. func (f *File) Cols(sheet string) (*Cols, error) {
  198. if err := checkSheetName(sheet); err != nil {
  199. return nil, err
  200. }
  201. name, ok := f.getSheetXMLPath(sheet)
  202. if !ok {
  203. return nil, ErrSheetNotExist{sheet}
  204. }
  205. if ws, ok := f.Sheet.Load(name); ok && ws != nil {
  206. worksheet := ws.(*xlsxWorksheet)
  207. worksheet.Lock()
  208. defer worksheet.Unlock()
  209. output, _ := xml.Marshal(worksheet)
  210. f.saveFileList(name, f.replaceNameSpaceBytes(name, output))
  211. }
  212. var colIterator columnXMLIterator
  213. colIterator.cols.sheetXML = f.readBytes(name)
  214. decoder := f.xmlNewDecoder(bytes.NewReader(colIterator.cols.sheetXML))
  215. for {
  216. token, _ := decoder.Token()
  217. if token == nil {
  218. break
  219. }
  220. switch xmlElement := token.(type) {
  221. case xml.StartElement:
  222. columnXMLHandler(&colIterator, &xmlElement)
  223. if colIterator.err != nil {
  224. return &colIterator.cols, colIterator.err
  225. }
  226. case xml.EndElement:
  227. if xmlElement.Name.Local == "sheetData" {
  228. colIterator.cols.f = f
  229. colIterator.cols.sheet = sheet
  230. return &colIterator.cols, nil
  231. }
  232. }
  233. }
  234. return &colIterator.cols, nil
  235. }
  236. // GetColVisible provides a function to get visible of a single column by given
  237. // worksheet name and column name. This function is concurrency safe. For
  238. // example, get visible state of column D in Sheet1:
  239. //
  240. // visible, err := f.GetColVisible("Sheet1", "D")
  241. func (f *File) GetColVisible(sheet, col string) (bool, error) {
  242. colNum, err := ColumnNameToNumber(col)
  243. if err != nil {
  244. return true, err
  245. }
  246. ws, err := f.workSheetReader(sheet)
  247. if err != nil {
  248. return false, err
  249. }
  250. ws.Lock()
  251. defer ws.Unlock()
  252. if ws.Cols == nil {
  253. return true, err
  254. }
  255. visible := true
  256. for c := range ws.Cols.Col {
  257. colData := &ws.Cols.Col[c]
  258. if colData.Min <= colNum && colNum <= colData.Max {
  259. visible = !colData.Hidden
  260. }
  261. }
  262. return visible, err
  263. }
  264. // SetColVisible provides a function to set visible columns by given worksheet
  265. // name, columns range and visibility. This function is concurrency safe.
  266. //
  267. // For example hide column D on Sheet1:
  268. //
  269. // err := f.SetColVisible("Sheet1", "D", false)
  270. //
  271. // Hide the columns from D to F (included):
  272. //
  273. // err := f.SetColVisible("Sheet1", "D:F", false)
  274. func (f *File) SetColVisible(sheet, columns string, visible bool) error {
  275. min, max, err := f.parseColRange(columns)
  276. if err != nil {
  277. return err
  278. }
  279. ws, err := f.workSheetReader(sheet)
  280. if err != nil {
  281. return err
  282. }
  283. ws.Lock()
  284. defer ws.Unlock()
  285. colData := xlsxCol{
  286. Min: min,
  287. Max: max,
  288. Width: float64Ptr(defaultColWidth),
  289. Hidden: !visible,
  290. CustomWidth: true,
  291. }
  292. if ws.Cols == nil {
  293. cols := xlsxCols{}
  294. cols.Col = append(cols.Col, colData)
  295. ws.Cols = &cols
  296. return nil
  297. }
  298. ws.Cols.Col = flatCols(colData, ws.Cols.Col, func(fc, c xlsxCol) xlsxCol {
  299. fc.BestFit = c.BestFit
  300. fc.Collapsed = c.Collapsed
  301. fc.CustomWidth = c.CustomWidth
  302. fc.OutlineLevel = c.OutlineLevel
  303. fc.Phonetic = c.Phonetic
  304. fc.Style = c.Style
  305. fc.Width = c.Width
  306. return fc
  307. })
  308. return nil
  309. }
  310. // GetColOutlineLevel provides a function to get outline level of a single
  311. // column by given worksheet name and column name. For example, get outline
  312. // level of column D in Sheet1:
  313. //
  314. // level, err := f.GetColOutlineLevel("Sheet1", "D")
  315. func (f *File) GetColOutlineLevel(sheet, col string) (uint8, error) {
  316. level := uint8(0)
  317. colNum, err := ColumnNameToNumber(col)
  318. if err != nil {
  319. return level, err
  320. }
  321. ws, err := f.workSheetReader(sheet)
  322. if err != nil {
  323. return 0, err
  324. }
  325. if ws.Cols == nil {
  326. return level, err
  327. }
  328. for c := range ws.Cols.Col {
  329. colData := &ws.Cols.Col[c]
  330. if colData.Min <= colNum && colNum <= colData.Max {
  331. level = colData.OutlineLevel
  332. }
  333. }
  334. return level, err
  335. }
  336. // parseColRange parse and convert column range with column name to the column number.
  337. func (f *File) parseColRange(columns string) (min, max int, err error) {
  338. colsTab := strings.Split(columns, ":")
  339. min, err = ColumnNameToNumber(colsTab[0])
  340. if err != nil {
  341. return
  342. }
  343. max = min
  344. if len(colsTab) == 2 {
  345. if max, err = ColumnNameToNumber(colsTab[1]); err != nil {
  346. return
  347. }
  348. }
  349. if max < min {
  350. min, max = max, min
  351. }
  352. return
  353. }
  354. // SetColOutlineLevel provides a function to set outline level of a single
  355. // column by given worksheet name and column name. The value of parameter
  356. // 'level' is 1-7. For example, set outline level of column D in Sheet1 to 2:
  357. //
  358. // err := f.SetColOutlineLevel("Sheet1", "D", 2)
  359. func (f *File) SetColOutlineLevel(sheet, col string, level uint8) error {
  360. if level > 7 || level < 1 {
  361. return ErrOutlineLevel
  362. }
  363. colNum, err := ColumnNameToNumber(col)
  364. if err != nil {
  365. return err
  366. }
  367. colData := xlsxCol{
  368. Min: colNum,
  369. Max: colNum,
  370. OutlineLevel: level,
  371. CustomWidth: true,
  372. }
  373. ws, err := f.workSheetReader(sheet)
  374. if err != nil {
  375. return err
  376. }
  377. if ws.Cols == nil {
  378. cols := xlsxCols{}
  379. cols.Col = append(cols.Col, colData)
  380. ws.Cols = &cols
  381. return err
  382. }
  383. ws.Cols.Col = flatCols(colData, ws.Cols.Col, func(fc, c xlsxCol) xlsxCol {
  384. fc.BestFit = c.BestFit
  385. fc.Collapsed = c.Collapsed
  386. fc.CustomWidth = c.CustomWidth
  387. fc.Hidden = c.Hidden
  388. fc.Phonetic = c.Phonetic
  389. fc.Style = c.Style
  390. fc.Width = c.Width
  391. return fc
  392. })
  393. return err
  394. }
  395. // SetColStyle provides a function to set style of columns by given worksheet
  396. // name, columns range and style ID. This function is concurrency safe. Note
  397. // that this will overwrite the existing styles for the columns, it won't
  398. // append or merge style with existing styles.
  399. //
  400. // For example set style of column H on Sheet1:
  401. //
  402. // err = f.SetColStyle("Sheet1", "H", style)
  403. //
  404. // Set style of columns C:F on Sheet1:
  405. //
  406. // err = f.SetColStyle("Sheet1", "C:F", style)
  407. func (f *File) SetColStyle(sheet, columns string, styleID int) error {
  408. min, max, err := f.parseColRange(columns)
  409. if err != nil {
  410. return err
  411. }
  412. s, err := f.stylesReader()
  413. if err != nil {
  414. return err
  415. }
  416. s.Lock()
  417. if styleID < 0 || s.CellXfs == nil || len(s.CellXfs.Xf) <= styleID {
  418. s.Unlock()
  419. return newInvalidStyleID(styleID)
  420. }
  421. s.Unlock()
  422. ws, err := f.workSheetReader(sheet)
  423. if err != nil {
  424. return err
  425. }
  426. ws.Lock()
  427. if ws.Cols == nil {
  428. ws.Cols = &xlsxCols{}
  429. }
  430. ws.Cols.Col = flatCols(xlsxCol{
  431. Min: min,
  432. Max: max,
  433. Width: float64Ptr(defaultColWidth),
  434. Style: styleID,
  435. }, ws.Cols.Col, func(fc, c xlsxCol) xlsxCol {
  436. fc.BestFit = c.BestFit
  437. fc.Collapsed = c.Collapsed
  438. fc.CustomWidth = c.CustomWidth
  439. fc.Hidden = c.Hidden
  440. fc.OutlineLevel = c.OutlineLevel
  441. fc.Phonetic = c.Phonetic
  442. fc.Width = c.Width
  443. return fc
  444. })
  445. ws.Unlock()
  446. if rows := len(ws.SheetData.Row); rows > 0 {
  447. for col := min; col <= max; col++ {
  448. from, _ := CoordinatesToCellName(col, 1)
  449. to, _ := CoordinatesToCellName(col, rows)
  450. err = f.SetCellStyle(sheet, from, to, styleID)
  451. }
  452. }
  453. return err
  454. }
  455. // SetColWidth provides a function to set the width of a single column or
  456. // multiple columns. This function is concurrency safe. For example:
  457. //
  458. // err := f.SetColWidth("Sheet1", "A", "H", 20)
  459. func (f *File) SetColWidth(sheet, startCol, endCol string, width float64) error {
  460. min, max, err := f.parseColRange(startCol + ":" + endCol)
  461. if err != nil {
  462. return err
  463. }
  464. if width > MaxColumnWidth {
  465. return ErrColumnWidth
  466. }
  467. ws, err := f.workSheetReader(sheet)
  468. if err != nil {
  469. return err
  470. }
  471. ws.Lock()
  472. defer ws.Unlock()
  473. col := xlsxCol{
  474. Min: min,
  475. Max: max,
  476. Width: float64Ptr(width),
  477. CustomWidth: true,
  478. }
  479. if ws.Cols == nil {
  480. cols := xlsxCols{}
  481. cols.Col = append(cols.Col, col)
  482. ws.Cols = &cols
  483. return err
  484. }
  485. ws.Cols.Col = flatCols(col, ws.Cols.Col, func(fc, c xlsxCol) xlsxCol {
  486. fc.BestFit = c.BestFit
  487. fc.Collapsed = c.Collapsed
  488. fc.Hidden = c.Hidden
  489. fc.OutlineLevel = c.OutlineLevel
  490. fc.Phonetic = c.Phonetic
  491. fc.Style = c.Style
  492. return fc
  493. })
  494. return err
  495. }
  496. // flatCols provides a method for the column's operation functions to flatten
  497. // and check the worksheet columns.
  498. func flatCols(col xlsxCol, cols []xlsxCol, replacer func(fc, c xlsxCol) xlsxCol) []xlsxCol {
  499. var fc []xlsxCol
  500. for i := col.Min; i <= col.Max; i++ {
  501. c := deepcopy.Copy(col).(xlsxCol)
  502. c.Min, c.Max = i, i
  503. fc = append(fc, c)
  504. }
  505. inFlat := func(colID int, cols []xlsxCol) (int, bool) {
  506. for idx, c := range cols {
  507. if c.Max == colID && c.Min == colID {
  508. return idx, true
  509. }
  510. }
  511. return -1, false
  512. }
  513. for _, column := range cols {
  514. for i := column.Min; i <= column.Max; i++ {
  515. if idx, ok := inFlat(i, fc); ok {
  516. fc[idx] = replacer(fc[idx], column)
  517. continue
  518. }
  519. c := deepcopy.Copy(column).(xlsxCol)
  520. c.Min, c.Max = i, i
  521. fc = append(fc, c)
  522. }
  523. }
  524. return fc
  525. }
  526. // positionObjectPixels calculate the vertices that define the position of a
  527. // graphical object within the worksheet in pixels.
  528. //
  529. // +------------+------------+
  530. // | A | B |
  531. // +-----+------------+------------+
  532. // | |(x1,y1) | |
  533. // | 1 |(A1)._______|______ |
  534. // | | | | |
  535. // | | | | |
  536. // +-----+----| OBJECT |-----+
  537. // | | | | |
  538. // | 2 | |______________. |
  539. // | | | (B2)|
  540. // | | | (x2,y2)|
  541. // +-----+------------+------------+
  542. //
  543. // Example of an object that covers some range reference from cell A1 to B2.
  544. //
  545. // Based on the width and height of the object we need to calculate 8 vars:
  546. //
  547. // colStart, rowStart, colEnd, rowEnd, x1, y1, x2, y2.
  548. //
  549. // We also calculate the absolute x and y position of the top left vertex of
  550. // the object. This is required for images.
  551. //
  552. // The width and height of the cells that the object occupies can be
  553. // variable and have to be taken into account.
  554. //
  555. // The values of col_start and row_start are passed in from the calling
  556. // function. The values of col_end and row_end are calculated by
  557. // subtracting the width and height of the object from the width and
  558. // height of the underlying cells.
  559. //
  560. // colStart # Col containing upper left corner of object.
  561. // x1 # Distance to left side of object.
  562. //
  563. // rowStart # Row containing top left corner of object.
  564. // y1 # Distance to top of object.
  565. //
  566. // colEnd # Col containing lower right corner of object.
  567. // x2 # Distance to right side of object.
  568. //
  569. // rowEnd # Row containing bottom right corner of object.
  570. // y2 # Distance to bottom of object.
  571. //
  572. // width # Width of object frame.
  573. // height # Height of object frame.
  574. func (f *File) positionObjectPixels(sheet string, col, row, x1, y1, width, height int) (int, int, int, int, int, int) {
  575. // Adjust start column for offsets that are greater than the col width.
  576. for x1 >= f.getColWidth(sheet, col) {
  577. x1 -= f.getColWidth(sheet, col)
  578. col++
  579. }
  580. // Adjust start row for offsets that are greater than the row height.
  581. for y1 >= f.getRowHeight(sheet, row) {
  582. y1 -= f.getRowHeight(sheet, row)
  583. row++
  584. }
  585. // Initialized end cell to the same as the start cell.
  586. colEnd, rowEnd := col, row
  587. width += x1
  588. height += y1
  589. // Subtract the underlying cell widths to find end cell of the object.
  590. for width >= f.getColWidth(sheet, colEnd+1) {
  591. colEnd++
  592. width -= f.getColWidth(sheet, colEnd)
  593. }
  594. // Subtract the underlying cell heights to find end cell of the object.
  595. for height >= f.getRowHeight(sheet, rowEnd+1) {
  596. rowEnd++
  597. height -= f.getRowHeight(sheet, rowEnd)
  598. }
  599. // The end vertices are whatever is left from the width and height.
  600. x2 := width
  601. y2 := height
  602. return col, row, colEnd, rowEnd, x2, y2
  603. }
  604. // getColWidth provides a function to get column width in pixels by given
  605. // sheet name and column number.
  606. func (f *File) getColWidth(sheet string, col int) int {
  607. ws, _ := f.workSheetReader(sheet)
  608. ws.Lock()
  609. defer ws.Unlock()
  610. if ws.Cols != nil {
  611. var width float64
  612. for _, v := range ws.Cols.Col {
  613. if v.Min <= col && col <= v.Max && v.Width != nil {
  614. width = *v.Width
  615. }
  616. }
  617. if width != 0 {
  618. return int(convertColWidthToPixels(width))
  619. }
  620. }
  621. // Optimization for when the column widths haven't changed.
  622. return int(defaultColWidthPixels)
  623. }
  624. // GetColStyle provides a function to get column style ID by given worksheet
  625. // name and column name. This function is concurrency safe.
  626. func (f *File) GetColStyle(sheet, col string) (int, error) {
  627. var styleID int
  628. colNum, err := ColumnNameToNumber(col)
  629. if err != nil {
  630. return styleID, err
  631. }
  632. ws, err := f.workSheetReader(sheet)
  633. if err != nil {
  634. return styleID, err
  635. }
  636. ws.Lock()
  637. defer ws.Unlock()
  638. if ws.Cols != nil {
  639. for _, v := range ws.Cols.Col {
  640. if v.Min <= colNum && colNum <= v.Max {
  641. styleID = v.Style
  642. }
  643. }
  644. }
  645. return styleID, err
  646. }
  647. // GetColWidth provides a function to get column width by given worksheet name
  648. // and column name. This function is concurrency safe.
  649. func (f *File) GetColWidth(sheet, col string) (float64, error) {
  650. colNum, err := ColumnNameToNumber(col)
  651. if err != nil {
  652. return defaultColWidth, err
  653. }
  654. ws, err := f.workSheetReader(sheet)
  655. if err != nil {
  656. return defaultColWidth, err
  657. }
  658. ws.Lock()
  659. defer ws.Unlock()
  660. if ws.Cols != nil {
  661. var width float64
  662. for _, v := range ws.Cols.Col {
  663. if v.Min <= colNum && colNum <= v.Max && v.Width != nil {
  664. width = *v.Width
  665. }
  666. }
  667. if width != 0 {
  668. return width, err
  669. }
  670. }
  671. // Optimization for when the column widths haven't changed.
  672. return defaultColWidth, err
  673. }
  674. // InsertCols provides a function to insert new columns before the given column
  675. // name and number of columns. For example, create two columns before column
  676. // C in Sheet1:
  677. //
  678. // err := f.InsertCols("Sheet1", "C", 2)
  679. //
  680. // Use this method with caution, which will affect changes in references such
  681. // as formulas, charts, and so on. If there is any referenced value of the
  682. // worksheet, it will cause a file error when you open it. The excelize only
  683. // partially updates these references currently.
  684. func (f *File) InsertCols(sheet, col string, n int) error {
  685. num, err := ColumnNameToNumber(col)
  686. if err != nil {
  687. return err
  688. }
  689. if n < 1 || n > MaxColumns {
  690. return ErrColumnNumber
  691. }
  692. return f.adjustHelper(sheet, columns, num, n)
  693. }
  694. // RemoveCol provides a function to remove single column by given worksheet
  695. // name and column index. For example, remove column C in Sheet1:
  696. //
  697. // err := f.RemoveCol("Sheet1", "C")
  698. //
  699. // Use this method with caution, which will affect changes in references such
  700. // as formulas, charts, and so on. If there is any referenced value of the
  701. // worksheet, it will cause a file error when you open it. The excelize only
  702. // partially updates these references currently.
  703. func (f *File) RemoveCol(sheet, col string) error {
  704. num, err := ColumnNameToNumber(col)
  705. if err != nil {
  706. return err
  707. }
  708. ws, err := f.workSheetReader(sheet)
  709. if err != nil {
  710. return err
  711. }
  712. for rowIdx := range ws.SheetData.Row {
  713. rowData := &ws.SheetData.Row[rowIdx]
  714. for colIdx := range rowData.C {
  715. colName, _, _ := SplitCellName(rowData.C[colIdx].R)
  716. if colName == col {
  717. rowData.C = append(rowData.C[:colIdx], rowData.C[colIdx+1:]...)[:len(rowData.C)-1]
  718. break
  719. }
  720. }
  721. }
  722. return f.adjustHelper(sheet, columns, num, -1)
  723. }
  724. // convertColWidthToPixels provides function to convert the width of a cell
  725. // from user's units to pixels. Excel rounds the column width to the nearest
  726. // pixel. If the width hasn't been set by the user we use the default value.
  727. // If the column is hidden it has a value of zero.
  728. func convertColWidthToPixels(width float64) float64 {
  729. var padding float64 = 5
  730. var pixels float64
  731. var maxDigitWidth float64 = 7
  732. if width == 0 {
  733. return pixels
  734. }
  735. if width < 1 {
  736. pixels = (width * 12) + 0.5
  737. return math.Ceil(pixels)
  738. }
  739. pixels = (width*maxDigitWidth + 0.5) + padding
  740. return math.Ceil(pixels)
  741. }