rows.go 17 KB

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