rows.go 17 KB

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