rows.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657
  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. "bytes"
  12. "encoding/xml"
  13. "errors"
  14. "fmt"
  15. "io"
  16. "log"
  17. "math"
  18. "strconv"
  19. )
  20. // GetRows return all the rows in a sheet by given worksheet name (case
  21. // sensitive). For example:
  22. //
  23. // rows, err := f.Rows("Sheet1")
  24. // if err != nil {
  25. // fmt.Println(err)
  26. // return
  27. // }
  28. // for rows.Next() {
  29. // row, err := rows.Columns()
  30. // if err != nil {
  31. // fmt.Println(err)
  32. // }
  33. // for _, colCell := range row {
  34. // fmt.Print(colCell, "\t")
  35. // }
  36. // fmt.Println()
  37. // }
  38. //
  39. func (f *File) GetRows(sheet string) ([][]string, error) {
  40. rows, err := f.Rows(sheet)
  41. if err != nil {
  42. return nil, err
  43. }
  44. results := make([][]string, 0, 64)
  45. for rows.Next() {
  46. if rows.Error() != nil {
  47. break
  48. }
  49. row, err := rows.Columns()
  50. if err != nil {
  51. break
  52. }
  53. results = append(results, row)
  54. }
  55. return results, nil
  56. }
  57. // Rows defines an iterator to a sheet
  58. type Rows struct {
  59. err error
  60. curRow, totalRow, stashRow int
  61. sheet string
  62. rows []xlsxRow
  63. f *File
  64. decoder *xml.Decoder
  65. }
  66. // Next will return true if find the next row element.
  67. func (rows *Rows) Next() bool {
  68. rows.curRow++
  69. return rows.curRow <= rows.totalRow
  70. }
  71. // Error will return the error when the find next row element
  72. func (rows *Rows) Error() error {
  73. return rows.err
  74. }
  75. // Columns return the current row's column values
  76. func (rows *Rows) Columns() ([]string, error) {
  77. var (
  78. err error
  79. inElement string
  80. row, cellCol int
  81. columns []string
  82. )
  83. if rows.stashRow >= rows.curRow {
  84. return columns, err
  85. }
  86. d := rows.f.sharedStringsReader()
  87. for {
  88. token, _ := rows.decoder.Token()
  89. if token == nil {
  90. break
  91. }
  92. switch startElement := token.(type) {
  93. case xml.StartElement:
  94. inElement = startElement.Name.Local
  95. if inElement == "row" {
  96. for _, attr := range startElement.Attr {
  97. if attr.Name.Local == "r" {
  98. row, err = strconv.Atoi(attr.Value)
  99. if err != nil {
  100. return columns, err
  101. }
  102. if row > rows.curRow {
  103. rows.stashRow = row - 1
  104. return columns, err
  105. }
  106. }
  107. }
  108. }
  109. if inElement == "c" {
  110. colCell := xlsxC{}
  111. _ = rows.decoder.DecodeElement(&colCell, &startElement)
  112. cellCol, _, err = CellNameToCoordinates(colCell.R)
  113. if err != nil {
  114. return columns, err
  115. }
  116. blank := cellCol - len(columns)
  117. for i := 1; i < blank; i++ {
  118. columns = append(columns, "")
  119. }
  120. val, _ := colCell.getValueFrom(rows.f, d)
  121. columns = append(columns, val)
  122. }
  123. case xml.EndElement:
  124. inElement = startElement.Name.Local
  125. if inElement == "row" {
  126. return columns, err
  127. }
  128. }
  129. }
  130. return columns, err
  131. }
  132. // ErrSheetNotExist defines an error of sheet is not exist
  133. type ErrSheetNotExist struct {
  134. SheetName string
  135. }
  136. func (err ErrSheetNotExist) Error() string {
  137. return fmt.Sprintf("sheet %s is not exist", string(err.SheetName))
  138. }
  139. // Rows returns a rows iterator, used for streaming reading data for a
  140. // worksheet with a large data. For example:
  141. //
  142. // rows, err := f.Rows("Sheet1")
  143. // if err != nil {
  144. // fmt.Println(err)
  145. // return
  146. // }
  147. // for rows.Next() {
  148. // row, err := rows.Columns()
  149. // if err != nil {
  150. // fmt.Println(err)
  151. // }
  152. // for _, colCell := range row {
  153. // fmt.Print(colCell, "\t")
  154. // }
  155. // fmt.Println()
  156. // }
  157. //
  158. func (f *File) Rows(sheet string) (*Rows, error) {
  159. name, ok := f.sheetMap[trimSheetName(sheet)]
  160. if !ok {
  161. return nil, ErrSheetNotExist{sheet}
  162. }
  163. if f.Sheet[name] != nil {
  164. // flush data
  165. output, _ := xml.Marshal(f.Sheet[name])
  166. f.saveFileList(name, replaceRelationshipsNameSpaceBytes(output))
  167. }
  168. var (
  169. err error
  170. inElement string
  171. row int
  172. rows Rows
  173. )
  174. decoder := f.xmlNewDecoder(bytes.NewReader(f.readXML(name)))
  175. for {
  176. token, _ := decoder.Token()
  177. if token == nil {
  178. break
  179. }
  180. switch startElement := token.(type) {
  181. case xml.StartElement:
  182. inElement = startElement.Name.Local
  183. if inElement == "row" {
  184. for _, attr := range startElement.Attr {
  185. if attr.Name.Local == "r" {
  186. row, err = strconv.Atoi(attr.Value)
  187. if err != nil {
  188. return &rows, err
  189. }
  190. }
  191. }
  192. rows.totalRow = row
  193. }
  194. default:
  195. }
  196. }
  197. rows.f = f
  198. rows.sheet = name
  199. rows.decoder = f.xmlNewDecoder(bytes.NewReader(f.readXML(name)))
  200. return &rows, nil
  201. }
  202. // SetRowHeight provides a function to set the height of a single row. For
  203. // example, set the height of the first row in Sheet1:
  204. //
  205. // err := f.SetRowHeight("Sheet1", 1, 50)
  206. //
  207. func (f *File) SetRowHeight(sheet string, row int, height float64) error {
  208. if row < 1 {
  209. return newInvalidRowNumberError(row)
  210. }
  211. xlsx, err := f.workSheetReader(sheet)
  212. if err != nil {
  213. return err
  214. }
  215. prepareSheetXML(xlsx, 0, row)
  216. rowIdx := row - 1
  217. xlsx.SheetData.Row[rowIdx].Ht = height
  218. xlsx.SheetData.Row[rowIdx].CustomHeight = true
  219. return nil
  220. }
  221. // getRowHeight provides a function to get row height in pixels by given sheet
  222. // name and row index.
  223. func (f *File) getRowHeight(sheet string, row int) int {
  224. xlsx, _ := f.workSheetReader(sheet)
  225. for i := range xlsx.SheetData.Row {
  226. v := &xlsx.SheetData.Row[i]
  227. if v.R == row+1 && v.Ht != 0 {
  228. return int(convertRowHeightToPixels(v.Ht))
  229. }
  230. }
  231. // Optimisation for when the row heights haven't changed.
  232. return int(defaultRowHeightPixels)
  233. }
  234. // GetRowHeight provides a function to get row height by given worksheet name
  235. // and row index. For example, get the height of the first row in Sheet1:
  236. //
  237. // height, err := f.GetRowHeight("Sheet1", 1)
  238. //
  239. func (f *File) GetRowHeight(sheet string, row int) (float64, error) {
  240. if row < 1 {
  241. return defaultRowHeightPixels, newInvalidRowNumberError(row)
  242. }
  243. xlsx, err := f.workSheetReader(sheet)
  244. if err != nil {
  245. return defaultRowHeightPixels, err
  246. }
  247. if row > len(xlsx.SheetData.Row) {
  248. return defaultRowHeightPixels, nil // it will be better to use 0, but we take care with BC
  249. }
  250. for _, v := range xlsx.SheetData.Row {
  251. if v.R == row && v.Ht != 0 {
  252. return v.Ht, nil
  253. }
  254. }
  255. // Optimisation for when the row heights haven't changed.
  256. return defaultRowHeightPixels, nil
  257. }
  258. // sharedStringsReader provides a function to get the pointer to the structure
  259. // after deserialization of xl/sharedStrings.xml.
  260. func (f *File) sharedStringsReader() *xlsxSST {
  261. var err error
  262. if f.SharedStrings == nil {
  263. var sharedStrings xlsxSST
  264. ss := f.readXML("xl/sharedStrings.xml")
  265. if len(ss) == 0 {
  266. ss = f.readXML("xl/SharedStrings.xml")
  267. }
  268. if err = f.xmlNewDecoder(bytes.NewReader(namespaceStrictToTransitional(ss))).
  269. Decode(&sharedStrings); err != nil && err != io.EOF {
  270. log.Printf("xml decode error: %s", err)
  271. }
  272. f.SharedStrings = &sharedStrings
  273. }
  274. return f.SharedStrings
  275. }
  276. // getValueFrom return a value from a column/row cell, this function is
  277. // inteded to be used with for range on rows an argument with the xlsx opened
  278. // file.
  279. func (xlsx *xlsxC) getValueFrom(f *File, d *xlsxSST) (string, error) {
  280. switch xlsx.T {
  281. case "s":
  282. if xlsx.V != "" {
  283. xlsxSI := 0
  284. xlsxSI, _ = strconv.Atoi(xlsx.V)
  285. if len(d.SI) > xlsxSI {
  286. return f.formattedValue(xlsx.S, d.SI[xlsxSI].String()), nil
  287. }
  288. }
  289. return f.formattedValue(xlsx.S, xlsx.V), nil
  290. case "str":
  291. return f.formattedValue(xlsx.S, xlsx.V), nil
  292. case "inlineStr":
  293. if xlsx.IS != nil {
  294. return f.formattedValue(xlsx.S, xlsx.IS.String()), nil
  295. }
  296. return f.formattedValue(xlsx.S, xlsx.V), nil
  297. default:
  298. return f.formattedValue(xlsx.S, xlsx.V), nil
  299. }
  300. }
  301. // SetRowVisible provides a function to set visible of a single row by given
  302. // worksheet name and Excel row number. For example, hide row 2 in Sheet1:
  303. //
  304. // err := f.SetRowVisible("Sheet1", 2, false)
  305. //
  306. func (f *File) SetRowVisible(sheet string, row int, visible bool) error {
  307. if row < 1 {
  308. return newInvalidRowNumberError(row)
  309. }
  310. xlsx, err := f.workSheetReader(sheet)
  311. if err != nil {
  312. return err
  313. }
  314. prepareSheetXML(xlsx, 0, row)
  315. xlsx.SheetData.Row[row-1].Hidden = !visible
  316. return nil
  317. }
  318. // GetRowVisible provides a function to get visible of a single row by given
  319. // worksheet name and Excel row number. For example, get visible state of row
  320. // 2 in Sheet1:
  321. //
  322. // visible, err := f.GetRowVisible("Sheet1", 2)
  323. //
  324. func (f *File) GetRowVisible(sheet string, row int) (bool, error) {
  325. if row < 1 {
  326. return false, newInvalidRowNumberError(row)
  327. }
  328. xlsx, err := f.workSheetReader(sheet)
  329. if err != nil {
  330. return false, err
  331. }
  332. if row > len(xlsx.SheetData.Row) {
  333. return false, nil
  334. }
  335. return !xlsx.SheetData.Row[row-1].Hidden, nil
  336. }
  337. // SetRowOutlineLevel provides a function to set outline level number of a
  338. // single row by given worksheet name and Excel row number. The value of
  339. // parameter 'level' is 1-7. For example, outline row 2 in Sheet1 to level 1:
  340. //
  341. // err := f.SetRowOutlineLevel("Sheet1", 2, 1)
  342. //
  343. func (f *File) SetRowOutlineLevel(sheet string, row int, level uint8) error {
  344. if row < 1 {
  345. return newInvalidRowNumberError(row)
  346. }
  347. if level > 7 || level < 1 {
  348. return errors.New("invalid outline level")
  349. }
  350. xlsx, err := f.workSheetReader(sheet)
  351. if err != nil {
  352. return err
  353. }
  354. prepareSheetXML(xlsx, 0, row)
  355. xlsx.SheetData.Row[row-1].OutlineLevel = level
  356. return nil
  357. }
  358. // GetRowOutlineLevel provides a function to get outline level number of a
  359. // single row by given worksheet name and Excel row number. For example, get
  360. // outline number of row 2 in Sheet1:
  361. //
  362. // level, err := f.GetRowOutlineLevel("Sheet1", 2)
  363. //
  364. func (f *File) GetRowOutlineLevel(sheet string, row int) (uint8, error) {
  365. if row < 1 {
  366. return 0, newInvalidRowNumberError(row)
  367. }
  368. xlsx, err := f.workSheetReader(sheet)
  369. if err != nil {
  370. return 0, err
  371. }
  372. if row > len(xlsx.SheetData.Row) {
  373. return 0, nil
  374. }
  375. return xlsx.SheetData.Row[row-1].OutlineLevel, nil
  376. }
  377. // RemoveRow provides a function to remove single row by given worksheet name
  378. // and Excel row number. For example, remove row 3 in Sheet1:
  379. //
  380. // err := f.RemoveRow("Sheet1", 3)
  381. //
  382. // Use this method with caution, which will affect changes in references such
  383. // as formulas, charts, and so on. If there is any referenced value of the
  384. // worksheet, it will cause a file error when you open it. The excelize only
  385. // partially updates these references currently.
  386. func (f *File) RemoveRow(sheet string, row int) error {
  387. if row < 1 {
  388. return newInvalidRowNumberError(row)
  389. }
  390. xlsx, err := f.workSheetReader(sheet)
  391. if err != nil {
  392. return err
  393. }
  394. if row > len(xlsx.SheetData.Row) {
  395. return f.adjustHelper(sheet, rows, row, -1)
  396. }
  397. keep := 0
  398. for rowIdx := 0; rowIdx < len(xlsx.SheetData.Row); rowIdx++ {
  399. v := &xlsx.SheetData.Row[rowIdx]
  400. if v.R != row {
  401. xlsx.SheetData.Row[keep] = *v
  402. keep++
  403. }
  404. }
  405. xlsx.SheetData.Row = xlsx.SheetData.Row[:keep]
  406. return f.adjustHelper(sheet, rows, row, -1)
  407. }
  408. // InsertRow provides a function to insert a new row after given Excel row
  409. // number starting from 1. For example, create a new row before row 3 in
  410. // Sheet1:
  411. //
  412. // err := f.InsertRow("Sheet1", 3)
  413. //
  414. // Use this method with caution, which will affect changes in references such
  415. // as formulas, charts, and so on. If there is any referenced value of the
  416. // worksheet, it will cause a file error when you open it. The excelize only
  417. // partially updates these references currently.
  418. func (f *File) InsertRow(sheet string, row int) error {
  419. if row < 1 {
  420. return newInvalidRowNumberError(row)
  421. }
  422. return f.adjustHelper(sheet, rows, row, 1)
  423. }
  424. // DuplicateRow inserts a copy of specified row (by its Excel row number) below
  425. //
  426. // err := f.DuplicateRow("Sheet1", 2)
  427. //
  428. // Use this method with caution, which will affect changes in references such
  429. // as formulas, charts, and so on. If there is any referenced value of the
  430. // worksheet, it will cause a file error when you open it. The excelize only
  431. // partially updates these references currently.
  432. func (f *File) DuplicateRow(sheet string, row int) error {
  433. return f.DuplicateRowTo(sheet, row, row+1)
  434. }
  435. // DuplicateRowTo inserts a copy of specified row by it Excel number
  436. // to specified row position moving down exists rows after target position
  437. //
  438. // err := f.DuplicateRowTo("Sheet1", 2, 7)
  439. //
  440. // Use this method with caution, which will affect changes in references such
  441. // as formulas, charts, and so on. If there is any referenced value of the
  442. // worksheet, it will cause a file error when you open it. The excelize only
  443. // partially updates these references currently.
  444. func (f *File) DuplicateRowTo(sheet string, row, row2 int) error {
  445. if row < 1 {
  446. return newInvalidRowNumberError(row)
  447. }
  448. xlsx, err := f.workSheetReader(sheet)
  449. if err != nil {
  450. return err
  451. }
  452. if row > len(xlsx.SheetData.Row) || row2 < 1 || row == row2 {
  453. return nil
  454. }
  455. var ok bool
  456. var rowCopy xlsxRow
  457. for i, r := range xlsx.SheetData.Row {
  458. if r.R == row {
  459. rowCopy = xlsx.SheetData.Row[i]
  460. ok = true
  461. break
  462. }
  463. }
  464. if !ok {
  465. return nil
  466. }
  467. if err := f.adjustHelper(sheet, rows, row2, 1); err != nil {
  468. return err
  469. }
  470. idx2 := -1
  471. for i, r := range xlsx.SheetData.Row {
  472. if r.R == row2 {
  473. idx2 = i
  474. break
  475. }
  476. }
  477. if idx2 == -1 && len(xlsx.SheetData.Row) >= row2 {
  478. return nil
  479. }
  480. rowCopy.C = append(make([]xlsxC, 0, len(rowCopy.C)), rowCopy.C...)
  481. f.ajustSingleRowDimensions(&rowCopy, row2)
  482. if idx2 != -1 {
  483. xlsx.SheetData.Row[idx2] = rowCopy
  484. } else {
  485. xlsx.SheetData.Row = append(xlsx.SheetData.Row, rowCopy)
  486. }
  487. return f.duplicateMergeCells(sheet, xlsx, row, row2)
  488. }
  489. // duplicateMergeCells merge cells in the destination row if there are single
  490. // row merged cells in the copied row.
  491. func (f *File) duplicateMergeCells(sheet string, xlsx *xlsxWorksheet, row, row2 int) error {
  492. if xlsx.MergeCells == nil {
  493. return nil
  494. }
  495. if row > row2 {
  496. row++
  497. }
  498. for _, rng := range xlsx.MergeCells.Cells {
  499. coordinates, err := f.areaRefToCoordinates(rng.Ref)
  500. if err != nil {
  501. return err
  502. }
  503. if coordinates[1] < row2 && row2 < coordinates[3] {
  504. return nil
  505. }
  506. }
  507. for i := 0; i < len(xlsx.MergeCells.Cells); i++ {
  508. areaData := xlsx.MergeCells.Cells[i]
  509. coordinates, _ := f.areaRefToCoordinates(areaData.Ref)
  510. x1, y1, x2, y2 := coordinates[0], coordinates[1], coordinates[2], coordinates[3]
  511. if y1 == y2 && y1 == row {
  512. from, _ := CoordinatesToCellName(x1, row2)
  513. to, _ := CoordinatesToCellName(x2, row2)
  514. if err := f.MergeCell(sheet, from, to); err != nil {
  515. return err
  516. }
  517. i++
  518. }
  519. }
  520. return nil
  521. }
  522. // checkRow provides a function to check and fill each column element for all
  523. // rows and make that is continuous in a worksheet of XML. For example:
  524. //
  525. // <row r="15" spans="1:22" x14ac:dyDescent="0.2">
  526. // <c r="A15" s="2" />
  527. // <c r="B15" s="2" />
  528. // <c r="F15" s="1" />
  529. // <c r="G15" s="1" />
  530. // </row>
  531. //
  532. // in this case, we should to change it to
  533. //
  534. // <row r="15" spans="1:22" x14ac:dyDescent="0.2">
  535. // <c r="A15" s="2" />
  536. // <c r="B15" s="2" />
  537. // <c r="C15" s="2" />
  538. // <c r="D15" s="2" />
  539. // <c r="E15" s="2" />
  540. // <c r="F15" s="1" />
  541. // <c r="G15" s="1" />
  542. // </row>
  543. //
  544. // Noteice: this method could be very slow for large spreadsheets (more than
  545. // 3000 rows one sheet).
  546. func checkRow(xlsx *xlsxWorksheet) error {
  547. for rowIdx := range xlsx.SheetData.Row {
  548. rowData := &xlsx.SheetData.Row[rowIdx]
  549. colCount := len(rowData.C)
  550. if colCount == 0 {
  551. continue
  552. }
  553. // check and fill the cell without r attribute in a row element
  554. rCount := 0
  555. for idx, cell := range rowData.C {
  556. rCount++
  557. if cell.R != "" {
  558. lastR, _, err := CellNameToCoordinates(cell.R)
  559. if err != nil {
  560. return err
  561. }
  562. if lastR > rCount {
  563. rCount = lastR
  564. }
  565. continue
  566. }
  567. rowData.C[idx].R, _ = CoordinatesToCellName(rCount, rowIdx+1)
  568. }
  569. lastCol, _, err := CellNameToCoordinates(rowData.C[colCount-1].R)
  570. if err != nil {
  571. return err
  572. }
  573. if colCount < lastCol {
  574. oldList := rowData.C
  575. newlist := make([]xlsxC, 0, lastCol)
  576. rowData.C = xlsx.SheetData.Row[rowIdx].C[:0]
  577. for colIdx := 0; colIdx < lastCol; colIdx++ {
  578. cellName, err := CoordinatesToCellName(colIdx+1, rowIdx+1)
  579. if err != nil {
  580. return err
  581. }
  582. newlist = append(newlist, xlsxC{R: cellName})
  583. }
  584. rowData.C = newlist
  585. for colIdx := range oldList {
  586. colData := &oldList[colIdx]
  587. colNum, _, err := CellNameToCoordinates(colData.R)
  588. if err != nil {
  589. return err
  590. }
  591. xlsx.SheetData.Row[rowIdx].C[colNum-1] = *colData
  592. }
  593. }
  594. }
  595. return nil
  596. }
  597. // convertRowHeightToPixels provides a function to convert the height of a
  598. // cell from user's units to pixels. If the height hasn't been set by the user
  599. // we use the default value. If the row is hidden it has a value of zero.
  600. func convertRowHeightToPixels(height float64) float64 {
  601. var pixels float64
  602. if height == 0 {
  603. return pixels
  604. }
  605. pixels = math.Ceil(4.0 / 3.0 * height)
  606. return pixels
  607. }