rows.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. // Copyright 2016 - 2019 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.8 or later.
  9. package excelize
  10. import (
  11. "bytes"
  12. "encoding/xml"
  13. "fmt"
  14. "io"
  15. "math"
  16. "strconv"
  17. "strings"
  18. )
  19. // GetRows return all the rows in a sheet by given worksheet name (case
  20. // sensitive). For example:
  21. //
  22. // for _, row := range xlsx.GetRows("Sheet1") {
  23. // for _, colCell := range row {
  24. // fmt.Print(colCell, "\t")
  25. // }
  26. // fmt.Println()
  27. // }
  28. //
  29. func (f *File) GetRows(sheet string) [][]string {
  30. xlsx := f.workSheetReader(sheet)
  31. name, ok := f.sheetMap[trimSheetName(sheet)]
  32. if !ok {
  33. return [][]string{}
  34. }
  35. if xlsx != nil {
  36. output, _ := xml.Marshal(f.Sheet[name])
  37. f.saveFileList(name, replaceWorkSheetsRelationshipsNameSpaceBytes(output))
  38. }
  39. xml.NewDecoder(bytes.NewReader(f.readXML(name)))
  40. d := f.sharedStringsReader()
  41. var inElement string
  42. var r xlsxRow
  43. tr, tc := f.getTotalRowsCols(name)
  44. rows := make([][]string, tr)
  45. for i := range rows {
  46. rows[i] = make([]string, tc+1)
  47. }
  48. var row int
  49. decoder := xml.NewDecoder(bytes.NewReader(f.readXML(name)))
  50. for {
  51. token, _ := decoder.Token()
  52. if token == nil {
  53. break
  54. }
  55. switch startElement := token.(type) {
  56. case xml.StartElement:
  57. inElement = startElement.Name.Local
  58. if inElement == "row" {
  59. r = xlsxRow{}
  60. _ = decoder.DecodeElement(&r, &startElement)
  61. cr := r.R - 1
  62. for _, colCell := range r.C {
  63. c := TitleToNumber(strings.Map(letterOnlyMapF, colCell.R))
  64. val, _ := colCell.getValueFrom(f, d)
  65. rows[cr][c] = val
  66. if val != "" {
  67. row = r.R
  68. }
  69. }
  70. }
  71. default:
  72. }
  73. }
  74. return rows[:row]
  75. }
  76. // Rows defines an iterator to a sheet
  77. type Rows struct {
  78. decoder *xml.Decoder
  79. token xml.Token
  80. err error
  81. f *File
  82. }
  83. // Next will return true if find the next row element.
  84. func (rows *Rows) Next() bool {
  85. for {
  86. rows.token, rows.err = rows.decoder.Token()
  87. if rows.err == io.EOF {
  88. rows.err = nil
  89. }
  90. if rows.token == nil {
  91. return false
  92. }
  93. switch startElement := rows.token.(type) {
  94. case xml.StartElement:
  95. inElement := startElement.Name.Local
  96. if inElement == "row" {
  97. return true
  98. }
  99. }
  100. }
  101. }
  102. // Error will return the error when the find next row element
  103. func (rows *Rows) Error() error {
  104. return rows.err
  105. }
  106. // Columns return the current row's column values
  107. func (rows *Rows) Columns() []string {
  108. if rows.token == nil {
  109. return []string{}
  110. }
  111. startElement := rows.token.(xml.StartElement)
  112. r := xlsxRow{}
  113. _ = rows.decoder.DecodeElement(&r, &startElement)
  114. d := rows.f.sharedStringsReader()
  115. row := make([]string, len(r.C))
  116. for _, colCell := range r.C {
  117. c := TitleToNumber(strings.Map(letterOnlyMapF, colCell.R))
  118. val, _ := colCell.getValueFrom(rows.f, d)
  119. row[c] = val
  120. }
  121. return row
  122. }
  123. // ErrSheetNotExist defines an error of sheet is not exist
  124. type ErrSheetNotExist struct {
  125. SheetName string
  126. }
  127. func (err ErrSheetNotExist) Error() string {
  128. return fmt.Sprintf("Sheet %s is not exist", string(err.SheetName))
  129. }
  130. // Rows return a rows iterator. For example:
  131. //
  132. // rows, err := xlsx.Rows("Sheet1")
  133. // for rows.Next() {
  134. // for _, colCell := range rows.Columns() {
  135. // fmt.Print(colCell, "\t")
  136. // }
  137. // fmt.Println()
  138. // }
  139. //
  140. func (f *File) Rows(sheet string) (*Rows, error) {
  141. xlsx := f.workSheetReader(sheet)
  142. name, ok := f.sheetMap[trimSheetName(sheet)]
  143. if !ok {
  144. return nil, ErrSheetNotExist{sheet}
  145. }
  146. if xlsx != nil {
  147. output, _ := xml.Marshal(f.Sheet[name])
  148. f.saveFileList(name, replaceWorkSheetsRelationshipsNameSpaceBytes(output))
  149. }
  150. return &Rows{
  151. f: f,
  152. decoder: xml.NewDecoder(bytes.NewReader(f.readXML(name))),
  153. }, nil
  154. }
  155. // getTotalRowsCols provides a function to get total columns and rows in a
  156. // worksheet.
  157. func (f *File) getTotalRowsCols(name string) (int, int) {
  158. decoder := xml.NewDecoder(bytes.NewReader(f.readXML(name)))
  159. var inElement string
  160. var r xlsxRow
  161. var tr, tc int
  162. for {
  163. token, _ := decoder.Token()
  164. if token == nil {
  165. break
  166. }
  167. switch startElement := token.(type) {
  168. case xml.StartElement:
  169. inElement = startElement.Name.Local
  170. if inElement == "row" {
  171. r = xlsxRow{}
  172. _ = decoder.DecodeElement(&r, &startElement)
  173. tr = r.R
  174. for _, colCell := range r.C {
  175. col := TitleToNumber(strings.Map(letterOnlyMapF, colCell.R))
  176. if col > tc {
  177. tc = col
  178. }
  179. }
  180. }
  181. default:
  182. }
  183. }
  184. return tr, tc
  185. }
  186. // SetRowHeight provides a function to set the height of a single row. For
  187. // example, set the height of the first row in Sheet1:
  188. //
  189. // xlsx.SetRowHeight("Sheet1", 1, 50)
  190. //
  191. func (f *File) SetRowHeight(sheet string, row int, height float64) {
  192. xlsx := f.workSheetReader(sheet)
  193. if row < 1 {
  194. return
  195. }
  196. cells := 0
  197. rowIdx := row - 1
  198. completeRow(xlsx, row, cells)
  199. xlsx.SheetData.Row[rowIdx].Ht = height
  200. xlsx.SheetData.Row[rowIdx].CustomHeight = true
  201. }
  202. // getRowHeight provides a function to get row height in pixels by given sheet
  203. // name and row index.
  204. func (f *File) getRowHeight(sheet string, row int) int {
  205. xlsx := f.workSheetReader(sheet)
  206. for _, v := range xlsx.SheetData.Row {
  207. if v.R == row+1 && v.Ht != 0 {
  208. return int(convertRowHeightToPixels(v.Ht))
  209. }
  210. }
  211. // Optimisation for when the row heights haven't changed.
  212. return int(defaultRowHeightPixels)
  213. }
  214. // GetRowHeight provides a function to get row height by given worksheet name
  215. // and row index. For example, get the height of the first row in Sheet1:
  216. //
  217. // xlsx.GetRowHeight("Sheet1", 1)
  218. //
  219. func (f *File) GetRowHeight(sheet string, row int) float64 {
  220. xlsx := f.workSheetReader(sheet)
  221. if row < 1 || row > len(xlsx.SheetData.Row) {
  222. return defaultRowHeightPixels // it will be better to use 0, but we take care with BC
  223. }
  224. for _, v := range xlsx.SheetData.Row {
  225. if v.R == row && v.Ht != 0 {
  226. return v.Ht
  227. }
  228. }
  229. // Optimisation for when the row heights haven't changed.
  230. return defaultRowHeightPixels
  231. }
  232. // sharedStringsReader provides a function to get the pointer to the structure
  233. // after deserialization of xl/sharedStrings.xml.
  234. func (f *File) sharedStringsReader() *xlsxSST {
  235. if f.SharedStrings == nil {
  236. var sharedStrings xlsxSST
  237. ss := f.readXML("xl/sharedStrings.xml")
  238. if len(ss) == 0 {
  239. ss = f.readXML("xl/SharedStrings.xml")
  240. }
  241. _ = xml.Unmarshal(namespaceStrictToTransitional(ss), &sharedStrings)
  242. f.SharedStrings = &sharedStrings
  243. }
  244. return f.SharedStrings
  245. }
  246. // getValueFrom return a value from a column/row cell, this function is
  247. // inteded to be used with for range on rows an argument with the xlsx opened
  248. // file.
  249. func (xlsx *xlsxC) getValueFrom(f *File, d *xlsxSST) (string, error) {
  250. switch xlsx.T {
  251. case "s":
  252. xlsxSI := 0
  253. xlsxSI, _ = strconv.Atoi(xlsx.V)
  254. if len(d.SI[xlsxSI].R) > 0 {
  255. value := ""
  256. for _, v := range d.SI[xlsxSI].R {
  257. value += v.T
  258. }
  259. return value, nil
  260. }
  261. return f.formattedValue(xlsx.S, d.SI[xlsxSI].T), nil
  262. case "str":
  263. return f.formattedValue(xlsx.S, xlsx.V), nil
  264. case "inlineStr":
  265. return f.formattedValue(xlsx.S, xlsx.IS.T), nil
  266. default:
  267. return f.formattedValue(xlsx.S, xlsx.V), nil
  268. }
  269. }
  270. // SetRowVisible provides a function to set visible of a single row by given
  271. // worksheet name and Excel row number. For example, hide row 2 in Sheet1:
  272. //
  273. // xlsx.SetRowVisible("Sheet1", 2, false)
  274. //
  275. func (f *File) SetRowVisible(sheet string, row int, visible bool) {
  276. xlsx := f.workSheetReader(sheet)
  277. if row < 1 {
  278. return
  279. }
  280. cells := 0
  281. completeRow(xlsx, row, cells)
  282. rowIdx := row - 1
  283. if visible {
  284. xlsx.SheetData.Row[rowIdx].Hidden = false
  285. return
  286. }
  287. xlsx.SheetData.Row[rowIdx].Hidden = true
  288. }
  289. // GetRowVisible provides a function to get visible of a single row by given
  290. // worksheet name and Excel row number. For example, get visible state of row
  291. // 2 in Sheet1:
  292. //
  293. // xlsx.GetRowVisible("Sheet1", 2)
  294. //
  295. func (f *File) GetRowVisible(sheet string, row int) bool {
  296. xlsx := f.workSheetReader(sheet)
  297. if row < 1 || row > len(xlsx.SheetData.Row) {
  298. return false
  299. }
  300. rowIndex := row - 1
  301. cells := 0
  302. completeRow(xlsx, row, cells)
  303. return !xlsx.SheetData.Row[rowIndex].Hidden
  304. }
  305. // SetRowOutlineLevel provides a function to set outline level number of a
  306. // single row by given worksheet name and Excel row number. For example, outline row
  307. // 2 in Sheet1 to level 1:
  308. //
  309. // xlsx.SetRowOutlineLevel("Sheet1", 2, 1)
  310. //
  311. func (f *File) SetRowOutlineLevel(sheet string, row int, level uint8) {
  312. xlsx := f.workSheetReader(sheet)
  313. if row < 1 {
  314. return
  315. }
  316. cells := 0
  317. completeRow(xlsx, row, cells)
  318. xlsx.SheetData.Row[row-1].OutlineLevel = level
  319. }
  320. // GetRowOutlineLevel provides a function to get outline level number of a
  321. // single row by given worksheet name and Exce row number.
  322. // For example, get outline number of row 2 in Sheet1:
  323. //
  324. // xlsx.GetRowOutlineLevel("Sheet1", 2)
  325. //
  326. func (f *File) GetRowOutlineLevel(sheet string, row int) uint8 {
  327. xlsx := f.workSheetReader(sheet)
  328. if row < 1 || row > len(xlsx.SheetData.Row) {
  329. return 0
  330. }
  331. return xlsx.SheetData.Row[row-1].OutlineLevel
  332. }
  333. // RemoveRow provides a function to remove single row by given worksheet name
  334. // and Excel row number. For example, remove row 3 in Sheet1:
  335. //
  336. // xlsx.RemoveRow("Sheet1", 3)
  337. //
  338. // Use this method with caution, which will affect changes in references such
  339. // as formulas, charts, and so on. If there is any referenced value of the
  340. // worksheet, it will cause a file error when you open it. The excelize only
  341. // partially updates these references currently.
  342. func (f *File) RemoveRow(sheet string, row int) {
  343. xlsx := f.workSheetReader(sheet)
  344. if row < 1 || row > len(xlsx.SheetData.Row) {
  345. return
  346. }
  347. for i, r := range xlsx.SheetData.Row {
  348. if r.R == row {
  349. xlsx.SheetData.Row = append(xlsx.SheetData.Row[:i], xlsx.SheetData.Row[i+1:]...)
  350. f.adjustHelper(sheet, -1, row, -1)
  351. return
  352. }
  353. }
  354. }
  355. // InsertRow provides a function to insert a new row after given Excel row
  356. // number starting from 1. For example, create a new row before row 3 in
  357. // Sheet1:
  358. //
  359. // xlsx.InsertRow("Sheet1", 3)
  360. //
  361. func (f *File) InsertRow(sheet string, row int) {
  362. if row < 1 {
  363. return
  364. }
  365. f.adjustHelper(sheet, -1, row, 1)
  366. }
  367. // DuplicateRow inserts a copy of specified row (by it Excel row number) below
  368. //
  369. // xlsx.DuplicateRow("Sheet1", 2)
  370. //
  371. // Use this method with caution, which will affect changes in references such
  372. // as formulas, charts, and so on. If there is any referenced value of the
  373. // worksheet, it will cause a file error when you open it. The excelize only
  374. // partially updates these references currently.
  375. func (f *File) DuplicateRow(sheet string, row int) {
  376. f.DuplicateRowTo(sheet, row, row+1)
  377. }
  378. // DuplicateRowTo inserts a copy of specified row by it Excel number
  379. // to specified row position moving down exists rows after target position
  380. //
  381. // xlsx.DuplicateRowTo("Sheet1", 2, 7)
  382. //
  383. // Use this method with caution, which will affect changes in references such
  384. // as formulas, charts, and so on. If there is any referenced value of the
  385. // worksheet, it will cause a file error when you open it. The excelize only
  386. // partially updates these references currently.
  387. func (f *File) DuplicateRowTo(sheet string, row, row2 int) {
  388. xlsx := f.workSheetReader(sheet)
  389. if row < 1 || row > len(xlsx.SheetData.Row) || row2 < 1 || row == row2 {
  390. return
  391. }
  392. var ok bool
  393. var rowCopy xlsxRow
  394. for i, r := range xlsx.SheetData.Row {
  395. if r.R == row {
  396. rowCopy = xlsx.SheetData.Row[i]
  397. ok = true
  398. break
  399. }
  400. }
  401. if !ok {
  402. return
  403. }
  404. f.adjustHelper(sheet, -1, row2, 1)
  405. idx2 := -1
  406. for i, r := range xlsx.SheetData.Row {
  407. if r.R == row2 {
  408. idx2 = i
  409. break
  410. }
  411. }
  412. if idx2 == -1 && len(xlsx.SheetData.Row) >= row2 {
  413. return
  414. }
  415. rowCopy.C = append(make([]xlsxC, 0, len(rowCopy.C)), rowCopy.C...)
  416. f.ajustSingleRowDimensions(&rowCopy, row2)
  417. if idx2 != -1 {
  418. xlsx.SheetData.Row[idx2] = rowCopy
  419. } else {
  420. xlsx.SheetData.Row = append(xlsx.SheetData.Row, rowCopy)
  421. }
  422. }
  423. // checkRow provides a function to check and fill each column element for all
  424. // rows and make that is continuous in a worksheet of XML. For example:
  425. //
  426. // <row r="15" spans="1:22" x14ac:dyDescent="0.2">
  427. // <c r="A15" s="2" />
  428. // <c r="B15" s="2" />
  429. // <c r="F15" s="1" />
  430. // <c r="G15" s="1" />
  431. // </row>
  432. //
  433. // in this case, we should to change it to
  434. //
  435. // <row r="15" spans="1:22" x14ac:dyDescent="0.2">
  436. // <c r="A15" s="2" />
  437. // <c r="B15" s="2" />
  438. // <c r="C15" s="2" />
  439. // <c r="D15" s="2" />
  440. // <c r="E15" s="2" />
  441. // <c r="F15" s="1" />
  442. // <c r="G15" s="1" />
  443. // </row>
  444. //
  445. // Noteice: this method could be very slow for large spreadsheets (more than
  446. // 3000 rows one sheet).
  447. func checkRow(xlsx *xlsxWorksheet) {
  448. buffer := bytes.Buffer{}
  449. for k := range xlsx.SheetData.Row {
  450. lenCol := len(xlsx.SheetData.Row[k].C)
  451. if lenCol > 0 {
  452. endR := string(strings.Map(letterOnlyMapF, xlsx.SheetData.Row[k].C[lenCol-1].R))
  453. endRow, _ := strconv.Atoi(strings.Map(intOnlyMapF, xlsx.SheetData.Row[k].C[lenCol-1].R))
  454. endCol := TitleToNumber(endR) + 1
  455. if lenCol < endCol {
  456. oldRow := xlsx.SheetData.Row[k].C
  457. xlsx.SheetData.Row[k].C = xlsx.SheetData.Row[k].C[:0]
  458. var tmp []xlsxC
  459. for i := 0; i < endCol; i++ {
  460. buffer.WriteString(ToAlphaString(i))
  461. buffer.WriteString(strconv.Itoa(endRow))
  462. tmp = append(tmp, xlsxC{
  463. R: buffer.String(),
  464. })
  465. buffer.Reset()
  466. }
  467. xlsx.SheetData.Row[k].C = tmp
  468. for _, y := range oldRow {
  469. colAxis := TitleToNumber(string(strings.Map(letterOnlyMapF, y.R)))
  470. xlsx.SheetData.Row[k].C[colAxis] = y
  471. }
  472. }
  473. }
  474. }
  475. }
  476. // completeRow provides a function to check and fill each column element for a
  477. // single row and make that is continuous in a worksheet of XML by given row
  478. // index and axis.
  479. func completeRow(xlsx *xlsxWorksheet, row, cell int) {
  480. currentRows := len(xlsx.SheetData.Row)
  481. if currentRows > 1 {
  482. lastRow := xlsx.SheetData.Row[currentRows-1].R
  483. if lastRow >= row {
  484. row = lastRow
  485. }
  486. }
  487. for i := currentRows; i < row; i++ {
  488. xlsx.SheetData.Row = append(xlsx.SheetData.Row, xlsxRow{
  489. R: i + 1,
  490. })
  491. }
  492. buffer := bytes.Buffer{}
  493. for ii := currentRows; ii < row; ii++ {
  494. start := len(xlsx.SheetData.Row[ii].C)
  495. if start == 0 {
  496. for iii := start; iii < cell; iii++ {
  497. buffer.WriteString(ToAlphaString(iii))
  498. buffer.WriteString(strconv.Itoa(ii + 1))
  499. xlsx.SheetData.Row[ii].C = append(xlsx.SheetData.Row[ii].C, xlsxC{
  500. R: buffer.String(),
  501. })
  502. buffer.Reset()
  503. }
  504. }
  505. }
  506. }
  507. // convertRowHeightToPixels provides a function to convert the height of a
  508. // cell from user's units to pixels. If the height hasn't been set by the user
  509. // we use the default value. If the row is hidden it has a value of zero.
  510. func convertRowHeightToPixels(height float64) float64 {
  511. var pixels float64
  512. if height == 0 {
  513. return pixels
  514. }
  515. pixels = math.Ceil(4.0 / 3.0 * height)
  516. return pixels
  517. }