rows.go 18 KB

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