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 / 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. "fmt"
  17. "io"
  18. "log"
  19. "math"
  20. "strconv"
  21. )
  22. // GetRows return all the rows in a sheet by given worksheet name (case
  23. // sensitive). For example:
  24. //
  25. // rows, err := f.GetRows("Sheet1")
  26. // if err != nil {
  27. // fmt.Println(err)
  28. // return
  29. // }
  30. // for _, row := range rows {
  31. // for _, colCell := range row {
  32. // fmt.Print(colCell, "\t")
  33. // }
  34. // fmt.Println()
  35. // }
  36. //
  37. func (f *File) GetRows(sheet string) ([][]string, error) {
  38. rows, err := f.Rows(sheet)
  39. if err != nil {
  40. return nil, err
  41. }
  42. results := make([][]string, 0, 64)
  43. for rows.Next() {
  44. row, err := rows.Columns()
  45. if err != nil {
  46. break
  47. }
  48. results = append(results, row)
  49. }
  50. return results, nil
  51. }
  52. // Rows defines an iterator to a sheet.
  53. type Rows struct {
  54. err error
  55. curRow, totalRow, stashRow int
  56. sheet string
  57. rows []xlsxRow
  58. f *File
  59. decoder *xml.Decoder
  60. }
  61. // Next will return true if find the next row element.
  62. func (rows *Rows) Next() bool {
  63. rows.curRow++
  64. return rows.curRow <= rows.totalRow
  65. }
  66. // Error will return the error when the error occurs.
  67. func (rows *Rows) Error() error {
  68. return rows.err
  69. }
  70. // Columns return the current row's column values.
  71. func (rows *Rows) Columns() ([]string, error) {
  72. var (
  73. err error
  74. inElement string
  75. row, cellCol int
  76. columns []string
  77. )
  78. if rows.stashRow >= rows.curRow {
  79. return columns, err
  80. }
  81. d := rows.f.sharedStringsReader()
  82. for {
  83. token, _ := rows.decoder.Token()
  84. if token == nil {
  85. break
  86. }
  87. switch startElement := token.(type) {
  88. case xml.StartElement:
  89. inElement = startElement.Name.Local
  90. if inElement == "row" {
  91. for _, attr := range startElement.Attr {
  92. if attr.Name.Local == "r" {
  93. row, err = strconv.Atoi(attr.Value)
  94. if err != nil {
  95. return columns, err
  96. }
  97. if row > rows.curRow {
  98. rows.stashRow = row - 1
  99. return columns, err
  100. }
  101. }
  102. }
  103. }
  104. if inElement == "c" {
  105. cellCol++
  106. colCell := xlsxC{}
  107. _ = rows.decoder.DecodeElement(&colCell, &startElement)
  108. if colCell.R != "" {
  109. cellCol, _, err = CellNameToCoordinates(colCell.R)
  110. if err != nil {
  111. return columns, err
  112. }
  113. }
  114. blank := cellCol - len(columns)
  115. for i := 1; i < blank; i++ {
  116. columns = append(columns, "")
  117. }
  118. val, _ := colCell.getValueFrom(rows.f, d)
  119. columns = append(columns, val)
  120. }
  121. case xml.EndElement:
  122. inElement = startElement.Name.Local
  123. if inElement == "row" {
  124. return columns, err
  125. }
  126. }
  127. }
  128. return columns, err
  129. }
  130. // ErrSheetNotExist defines an error of sheet is not exist
  131. type ErrSheetNotExist struct {
  132. SheetName string
  133. }
  134. func (err ErrSheetNotExist) Error() string {
  135. return fmt.Sprintf("sheet %s is not exist", string(err.SheetName))
  136. }
  137. // Rows returns a rows iterator, used for streaming reading data for a
  138. // worksheet with a large data. For example:
  139. //
  140. // rows, err := f.Rows("Sheet1")
  141. // if err != nil {
  142. // fmt.Println(err)
  143. // return
  144. // }
  145. // for rows.Next() {
  146. // row, err := rows.Columns()
  147. // if err != nil {
  148. // fmt.Println(err)
  149. // }
  150. // for _, colCell := range row {
  151. // fmt.Print(colCell, "\t")
  152. // }
  153. // fmt.Println()
  154. // }
  155. //
  156. func (f *File) Rows(sheet string) (*Rows, error) {
  157. name, ok := f.sheetMap[trimSheetName(sheet)]
  158. if !ok {
  159. return nil, ErrSheetNotExist{sheet}
  160. }
  161. if f.Sheet[name] != nil {
  162. // flush data
  163. output, _ := xml.Marshal(f.Sheet[name])
  164. f.saveFileList(name, replaceRelationshipsNameSpaceBytes(output))
  165. }
  166. var (
  167. err error
  168. inElement string
  169. row int
  170. rows Rows
  171. )
  172. decoder := f.xmlNewDecoder(bytes.NewReader(f.readXML(name)))
  173. for {
  174. token, _ := decoder.Token()
  175. if token == nil {
  176. break
  177. }
  178. switch startElement := token.(type) {
  179. case xml.StartElement:
  180. inElement = startElement.Name.Local
  181. if inElement == "row" {
  182. 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 err = f.xmlNewDecoder(bytes.NewReader(namespaceStrictToTransitional(ss))).
  265. Decode(&sharedStrings); err != nil && err != io.EOF {
  266. log.Printf("xml decode error: %s", err)
  267. }
  268. f.SharedStrings = &sharedStrings
  269. for i := range sharedStrings.SI {
  270. if sharedStrings.SI[i].T != nil {
  271. f.sharedStringsMap[sharedStrings.SI[i].T.Val] = i
  272. }
  273. }
  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. }