rows.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  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. xlsxSI := 0
  282. xlsxSI, _ = strconv.Atoi(xlsx.V)
  283. if len(d.SI) > xlsxSI {
  284. return f.formattedValue(xlsx.S, d.SI[xlsxSI].String()), nil
  285. }
  286. return f.formattedValue(xlsx.S, xlsx.V), nil
  287. case "str":
  288. return f.formattedValue(xlsx.S, xlsx.V), nil
  289. case "inlineStr":
  290. if xlsx.IS != nil {
  291. return f.formattedValue(xlsx.S, xlsx.IS.String()), nil
  292. }
  293. return f.formattedValue(xlsx.S, xlsx.V), nil
  294. default:
  295. return f.formattedValue(xlsx.S, xlsx.V), nil
  296. }
  297. }
  298. // SetRowVisible provides a function to set visible of a single row by given
  299. // worksheet name and Excel row number. For example, hide row 2 in Sheet1:
  300. //
  301. // err := f.SetRowVisible("Sheet1", 2, false)
  302. //
  303. func (f *File) SetRowVisible(sheet string, row int, visible bool) error {
  304. if row < 1 {
  305. return newInvalidRowNumberError(row)
  306. }
  307. xlsx, err := f.workSheetReader(sheet)
  308. if err != nil {
  309. return err
  310. }
  311. prepareSheetXML(xlsx, 0, row)
  312. xlsx.SheetData.Row[row-1].Hidden = !visible
  313. return nil
  314. }
  315. // GetRowVisible provides a function to get visible of a single row by given
  316. // worksheet name and Excel row number. For example, get visible state of row
  317. // 2 in Sheet1:
  318. //
  319. // visible, err := f.GetRowVisible("Sheet1", 2)
  320. //
  321. func (f *File) GetRowVisible(sheet string, row int) (bool, error) {
  322. if row < 1 {
  323. return false, newInvalidRowNumberError(row)
  324. }
  325. xlsx, err := f.workSheetReader(sheet)
  326. if err != nil {
  327. return false, err
  328. }
  329. if row > len(xlsx.SheetData.Row) {
  330. return false, nil
  331. }
  332. return !xlsx.SheetData.Row[row-1].Hidden, nil
  333. }
  334. // SetRowOutlineLevel provides a function to set outline level number of a
  335. // single row by given worksheet name and Excel row number. The value of
  336. // parameter 'level' is 1-7. For example, outline row 2 in Sheet1 to level 1:
  337. //
  338. // err := f.SetRowOutlineLevel("Sheet1", 2, 1)
  339. //
  340. func (f *File) SetRowOutlineLevel(sheet string, row int, level uint8) error {
  341. if row < 1 {
  342. return newInvalidRowNumberError(row)
  343. }
  344. if level > 7 || level < 1 {
  345. return errors.New("invalid outline level")
  346. }
  347. xlsx, err := f.workSheetReader(sheet)
  348. if err != nil {
  349. return err
  350. }
  351. prepareSheetXML(xlsx, 0, row)
  352. xlsx.SheetData.Row[row-1].OutlineLevel = level
  353. return nil
  354. }
  355. // GetRowOutlineLevel provides a function to get outline level number of a
  356. // single row by given worksheet name and Excel row number. For example, get
  357. // outline number of row 2 in Sheet1:
  358. //
  359. // level, err := f.GetRowOutlineLevel("Sheet1", 2)
  360. //
  361. func (f *File) GetRowOutlineLevel(sheet string, row int) (uint8, error) {
  362. if row < 1 {
  363. return 0, newInvalidRowNumberError(row)
  364. }
  365. xlsx, err := f.workSheetReader(sheet)
  366. if err != nil {
  367. return 0, err
  368. }
  369. if row > len(xlsx.SheetData.Row) {
  370. return 0, nil
  371. }
  372. return xlsx.SheetData.Row[row-1].OutlineLevel, nil
  373. }
  374. // RemoveRow provides a function to remove single row by given worksheet name
  375. // and Excel row number. For example, remove row 3 in Sheet1:
  376. //
  377. // err := f.RemoveRow("Sheet1", 3)
  378. //
  379. // Use this method with caution, which will affect changes in references such
  380. // as formulas, charts, and so on. If there is any referenced value of the
  381. // worksheet, it will cause a file error when you open it. The excelize only
  382. // partially updates these references currently.
  383. func (f *File) RemoveRow(sheet string, row int) error {
  384. if row < 1 {
  385. return newInvalidRowNumberError(row)
  386. }
  387. xlsx, err := f.workSheetReader(sheet)
  388. if err != nil {
  389. return err
  390. }
  391. if row > len(xlsx.SheetData.Row) {
  392. return f.adjustHelper(sheet, rows, row, -1)
  393. }
  394. for rowIdx := range xlsx.SheetData.Row {
  395. if xlsx.SheetData.Row[rowIdx].R == row {
  396. xlsx.SheetData.Row = append(xlsx.SheetData.Row[:rowIdx],
  397. xlsx.SheetData.Row[rowIdx+1:]...)[:len(xlsx.SheetData.Row)-1]
  398. return f.adjustHelper(sheet, rows, row, -1)
  399. }
  400. }
  401. return nil
  402. }
  403. // InsertRow provides a function to insert a new row after given Excel row
  404. // number starting from 1. For example, create a new row before row 3 in
  405. // Sheet1:
  406. //
  407. // err := f.InsertRow("Sheet1", 3)
  408. //
  409. // Use this method with caution, which will affect changes in references such
  410. // as formulas, charts, and so on. If there is any referenced value of the
  411. // worksheet, it will cause a file error when you open it. The excelize only
  412. // partially updates these references currently.
  413. func (f *File) InsertRow(sheet string, row int) error {
  414. if row < 1 {
  415. return newInvalidRowNumberError(row)
  416. }
  417. return f.adjustHelper(sheet, rows, row, 1)
  418. }
  419. // DuplicateRow inserts a copy of specified row (by its Excel row number) below
  420. //
  421. // err := f.DuplicateRow("Sheet1", 2)
  422. //
  423. // Use this method with caution, which will affect changes in references such
  424. // as formulas, charts, and so on. If there is any referenced value of the
  425. // worksheet, it will cause a file error when you open it. The excelize only
  426. // partially updates these references currently.
  427. func (f *File) DuplicateRow(sheet string, row int) error {
  428. return f.DuplicateRowTo(sheet, row, row+1)
  429. }
  430. // DuplicateRowTo inserts a copy of specified row by it Excel number
  431. // to specified row position moving down exists rows after target position
  432. //
  433. // err := f.DuplicateRowTo("Sheet1", 2, 7)
  434. //
  435. // Use this method with caution, which will affect changes in references such
  436. // as formulas, charts, and so on. If there is any referenced value of the
  437. // worksheet, it will cause a file error when you open it. The excelize only
  438. // partially updates these references currently.
  439. func (f *File) DuplicateRowTo(sheet string, row, row2 int) error {
  440. if row < 1 {
  441. return newInvalidRowNumberError(row)
  442. }
  443. xlsx, err := f.workSheetReader(sheet)
  444. if err != nil {
  445. return err
  446. }
  447. if row > len(xlsx.SheetData.Row) || row2 < 1 || row == row2 {
  448. return nil
  449. }
  450. var ok bool
  451. var rowCopy xlsxRow
  452. for i, r := range xlsx.SheetData.Row {
  453. if r.R == row {
  454. rowCopy = xlsx.SheetData.Row[i]
  455. ok = true
  456. break
  457. }
  458. }
  459. if !ok {
  460. return nil
  461. }
  462. if err := f.adjustHelper(sheet, rows, row2, 1); err != nil {
  463. return err
  464. }
  465. idx2 := -1
  466. for i, r := range xlsx.SheetData.Row {
  467. if r.R == row2 {
  468. idx2 = i
  469. break
  470. }
  471. }
  472. if idx2 == -1 && len(xlsx.SheetData.Row) >= row2 {
  473. return nil
  474. }
  475. rowCopy.C = append(make([]xlsxC, 0, len(rowCopy.C)), rowCopy.C...)
  476. f.ajustSingleRowDimensions(&rowCopy, row2)
  477. if idx2 != -1 {
  478. xlsx.SheetData.Row[idx2] = rowCopy
  479. } else {
  480. xlsx.SheetData.Row = append(xlsx.SheetData.Row, rowCopy)
  481. }
  482. return f.duplicateMergeCells(sheet, xlsx, row, row2)
  483. }
  484. // duplicateMergeCells merge cells in the destination row if there are single
  485. // row merged cells in the copied row.
  486. func (f *File) duplicateMergeCells(sheet string, xlsx *xlsxWorksheet, row, row2 int) error {
  487. if xlsx.MergeCells == nil {
  488. return nil
  489. }
  490. if row > row2 {
  491. row++
  492. }
  493. for _, rng := range xlsx.MergeCells.Cells {
  494. coordinates, err := f.areaRefToCoordinates(rng.Ref)
  495. if err != nil {
  496. return err
  497. }
  498. if coordinates[1] < row2 && row2 < coordinates[3] {
  499. return nil
  500. }
  501. }
  502. for i := 0; i < len(xlsx.MergeCells.Cells); i++ {
  503. areaData := xlsx.MergeCells.Cells[i]
  504. coordinates, _ := f.areaRefToCoordinates(areaData.Ref)
  505. x1, y1, x2, y2 := coordinates[0], coordinates[1], coordinates[2], coordinates[3]
  506. if y1 == y2 && y1 == row {
  507. from, _ := CoordinatesToCellName(x1, row2)
  508. to, _ := CoordinatesToCellName(x2, row2)
  509. if err := f.MergeCell(sheet, from, to); err != nil {
  510. return err
  511. }
  512. i++
  513. }
  514. }
  515. return nil
  516. }
  517. // checkRow provides a function to check and fill each column element for all
  518. // rows and make that is continuous in a worksheet of XML. For example:
  519. //
  520. // <row r="15" spans="1:22" x14ac:dyDescent="0.2">
  521. // <c r="A15" s="2" />
  522. // <c r="B15" s="2" />
  523. // <c r="F15" s="1" />
  524. // <c r="G15" s="1" />
  525. // </row>
  526. //
  527. // in this case, we should to change it to
  528. //
  529. // <row r="15" spans="1:22" x14ac:dyDescent="0.2">
  530. // <c r="A15" s="2" />
  531. // <c r="B15" s="2" />
  532. // <c r="C15" s="2" />
  533. // <c r="D15" s="2" />
  534. // <c r="E15" s="2" />
  535. // <c r="F15" s="1" />
  536. // <c r="G15" s="1" />
  537. // </row>
  538. //
  539. // Noteice: this method could be very slow for large spreadsheets (more than
  540. // 3000 rows one sheet).
  541. func checkRow(xlsx *xlsxWorksheet) error {
  542. for rowIdx := range xlsx.SheetData.Row {
  543. rowData := &xlsx.SheetData.Row[rowIdx]
  544. colCount := len(rowData.C)
  545. if colCount == 0 {
  546. continue
  547. }
  548. lastCol, _, err := CellNameToCoordinates(rowData.C[colCount-1].R)
  549. if err != nil {
  550. return err
  551. }
  552. if colCount < lastCol {
  553. oldList := rowData.C
  554. newlist := make([]xlsxC, 0, lastCol)
  555. rowData.C = xlsx.SheetData.Row[rowIdx].C[:0]
  556. for colIdx := 0; colIdx < lastCol; colIdx++ {
  557. cellName, err := CoordinatesToCellName(colIdx+1, rowIdx+1)
  558. if err != nil {
  559. return err
  560. }
  561. newlist = append(newlist, xlsxC{R: cellName})
  562. }
  563. rowData.C = newlist
  564. for colIdx := range oldList {
  565. colData := &oldList[colIdx]
  566. colNum, _, err := CellNameToCoordinates(colData.R)
  567. if err != nil {
  568. return err
  569. }
  570. xlsx.SheetData.Row[rowIdx].C[colNum-1] = *colData
  571. }
  572. }
  573. }
  574. return nil
  575. }
  576. // convertRowHeightToPixels provides a function to convert the height of a
  577. // cell from user's units to pixels. If the height hasn't been set by the user
  578. // we use the default value. If the row is hidden it has a value of zero.
  579. func convertRowHeightToPixels(height float64) float64 {
  580. var pixels float64
  581. if height == 0 {
  582. return pixels
  583. }
  584. pixels = math.Ceil(4.0 / 3.0 * height)
  585. return pixels
  586. }