rows.go 18 KB

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