col.go 18 KB

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