rows.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  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. cells := 0
  194. rowIdx := row - 1
  195. completeRow(xlsx, row, cells)
  196. xlsx.SheetData.Row[rowIdx].Ht = height
  197. xlsx.SheetData.Row[rowIdx].CustomHeight = true
  198. }
  199. // getRowHeight provides a function to get row height in pixels by given sheet
  200. // name and row index.
  201. func (f *File) getRowHeight(sheet string, row int) int {
  202. xlsx := f.workSheetReader(sheet)
  203. for _, v := range xlsx.SheetData.Row {
  204. if v.R == row+1 && v.Ht != 0 {
  205. return int(convertRowHeightToPixels(v.Ht))
  206. }
  207. }
  208. // Optimisation for when the row heights haven't changed.
  209. return int(defaultRowHeightPixels)
  210. }
  211. // GetRowHeight provides a function to get row height by given worksheet name
  212. // and row index. For example, get the height of the first row in Sheet1:
  213. //
  214. // xlsx.GetRowHeight("Sheet1", 1)
  215. //
  216. func (f *File) GetRowHeight(sheet string, row int) float64 {
  217. xlsx := f.workSheetReader(sheet)
  218. for _, v := range xlsx.SheetData.Row {
  219. if v.R == row && v.Ht != 0 {
  220. return v.Ht
  221. }
  222. }
  223. // Optimisation for when the row heights haven't changed.
  224. return defaultRowHeightPixels
  225. }
  226. // sharedStringsReader provides a function to get the pointer to the structure
  227. // after deserialization of xl/sharedStrings.xml.
  228. func (f *File) sharedStringsReader() *xlsxSST {
  229. if f.SharedStrings == nil {
  230. var sharedStrings xlsxSST
  231. ss := f.readXML("xl/sharedStrings.xml")
  232. if len(ss) == 0 {
  233. ss = f.readXML("xl/SharedStrings.xml")
  234. }
  235. _ = xml.Unmarshal(namespaceStrictToTransitional(ss), &sharedStrings)
  236. f.SharedStrings = &sharedStrings
  237. }
  238. return f.SharedStrings
  239. }
  240. // getValueFrom return a value from a column/row cell, this function is
  241. // inteded to be used with for range on rows an argument with the xlsx opened
  242. // file.
  243. func (xlsx *xlsxC) getValueFrom(f *File, d *xlsxSST) (string, error) {
  244. switch xlsx.T {
  245. case "s":
  246. xlsxSI := 0
  247. xlsxSI, _ = strconv.Atoi(xlsx.V)
  248. if len(d.SI[xlsxSI].R) > 0 {
  249. value := ""
  250. for _, v := range d.SI[xlsxSI].R {
  251. value += v.T
  252. }
  253. return value, nil
  254. }
  255. return f.formattedValue(xlsx.S, d.SI[xlsxSI].T), nil
  256. case "str":
  257. return f.formattedValue(xlsx.S, xlsx.V), nil
  258. case "inlineStr":
  259. return f.formattedValue(xlsx.S, xlsx.IS.T), nil
  260. default:
  261. return f.formattedValue(xlsx.S, xlsx.V), nil
  262. }
  263. }
  264. // SetRowVisible provides a function to set visible of a single row by given
  265. // worksheet name and row index. For example, hide row 2 in Sheet1:
  266. //
  267. // xlsx.SetRowVisible("Sheet1", 2, false)
  268. //
  269. func (f *File) SetRowVisible(sheet string, rowIndex int, visible bool) {
  270. xlsx := f.workSheetReader(sheet)
  271. rows := rowIndex + 1
  272. cells := 0
  273. completeRow(xlsx, rows, cells)
  274. if visible {
  275. xlsx.SheetData.Row[rowIndex].Hidden = false
  276. return
  277. }
  278. xlsx.SheetData.Row[rowIndex].Hidden = true
  279. }
  280. // GetRowVisible provides a function to get visible of a single row by given
  281. // worksheet name and row index. For example, get visible state of row 2 in
  282. // Sheet1:
  283. //
  284. // xlsx.GetRowVisible("Sheet1", 2)
  285. //
  286. func (f *File) GetRowVisible(sheet string, rowIndex int) bool {
  287. xlsx := f.workSheetReader(sheet)
  288. rows := rowIndex + 1
  289. cells := 0
  290. completeRow(xlsx, rows, cells)
  291. return !xlsx.SheetData.Row[rowIndex].Hidden
  292. }
  293. // SetRowOutlineLevel provides a function to set outline level number of a
  294. // single row by given worksheet name and row index. For example, outline row
  295. // 2 in Sheet1 to level 1:
  296. //
  297. // xlsx.SetRowOutlineLevel("Sheet1", 2, 1)
  298. //
  299. func (f *File) SetRowOutlineLevel(sheet string, rowIndex int, level uint8) {
  300. xlsx := f.workSheetReader(sheet)
  301. rows := rowIndex + 1
  302. cells := 0
  303. completeRow(xlsx, rows, cells)
  304. xlsx.SheetData.Row[rowIndex].OutlineLevel = level
  305. }
  306. // GetRowOutlineLevel provides a function to get outline level number of a
  307. // single row by given worksheet name and row index. For example, get outline
  308. // number of row 2 in Sheet1:
  309. //
  310. // xlsx.GetRowOutlineLevel("Sheet1", 2)
  311. //
  312. func (f *File) GetRowOutlineLevel(sheet string, rowIndex int) uint8 {
  313. xlsx := f.workSheetReader(sheet)
  314. rows := rowIndex + 1
  315. cells := 0
  316. completeRow(xlsx, rows, cells)
  317. return xlsx.SheetData.Row[rowIndex].OutlineLevel
  318. }
  319. // RemoveRow provides a function to remove single row by given worksheet name
  320. // and row index. For example, remove row 3 in Sheet1:
  321. //
  322. // xlsx.RemoveRow("Sheet1", 2)
  323. //
  324. // Use this method with caution, which will affect changes in references such
  325. // as formulas, charts, and so on. If there is any referenced value of the
  326. // worksheet, it will cause a file error when you open it. The excelize only
  327. // partially updates these references currently.
  328. func (f *File) RemoveRow(sheet string, row int) {
  329. if row < 0 {
  330. return
  331. }
  332. xlsx := f.workSheetReader(sheet)
  333. row++
  334. for i, r := range xlsx.SheetData.Row {
  335. if r.R == row {
  336. xlsx.SheetData.Row = append(xlsx.SheetData.Row[:i], xlsx.SheetData.Row[i+1:]...)
  337. f.adjustHelper(sheet, -1, row, -1)
  338. return
  339. }
  340. }
  341. }
  342. // InsertRow provides a function to insert a new row after given row index.
  343. // For example, create a new row before row 3 in Sheet1:
  344. //
  345. // xlsx.InsertRow("Sheet1", 2)
  346. //
  347. func (f *File) InsertRow(sheet string, row int) {
  348. if row < 0 {
  349. return
  350. }
  351. row++
  352. f.adjustHelper(sheet, -1, row, 1)
  353. }
  354. // DuplicateRow inserts a copy of specified row below specified
  355. //
  356. // xlsx.DuplicateRow("Sheet1", 2)
  357. //
  358. // Use this method with caution, which will affect changes in references such
  359. // as formulas, charts, and so on. If there is any referenced value of the
  360. // worksheet, it will cause a file error when you open it. The excelize only
  361. // partially updates these references currently.
  362. func (f *File) DuplicateRow(sheet string, row int) {
  363. f.DuplicateRowTo(sheet, row, row+1)
  364. }
  365. // DuplicateRowTo inserts a copy of specified row at specified row position
  366. // moving down exists rows after target position
  367. //
  368. // xlsx.DuplicateRowTo("Sheet1", 2, 7)
  369. //
  370. // Use this method with caution, which will affect changes in references such
  371. // as formulas, charts, and so on. If there is any referenced value of the
  372. // worksheet, it will cause a file error when you open it. The excelize only
  373. // partially updates these references currently.
  374. func (f *File) DuplicateRowTo(sheet string, row, row2 int) {
  375. if row <= 0 || row2 <= 0 || row == row2 {
  376. return
  377. }
  378. ws := f.workSheetReader(sheet)
  379. var ok bool
  380. var rowCopy xlsxRow
  381. for i, r := range ws.SheetData.Row {
  382. if r.R == row {
  383. rowCopy = ws.SheetData.Row[i]
  384. ok = true
  385. break
  386. }
  387. }
  388. if !ok {
  389. return
  390. }
  391. f.adjustHelper(sheet, -1, row2, 1)
  392. idx2 := -1
  393. for i, r := range ws.SheetData.Row {
  394. if r.R == row2 {
  395. idx2 = i
  396. break
  397. }
  398. }
  399. if idx2 == -1 && len(ws.SheetData.Row) >= row2 {
  400. return
  401. }
  402. rowCopy.C = append(make([]xlsxC, 0, len(rowCopy.C)), rowCopy.C...)
  403. f.ajustSingleRowDimensions(&rowCopy, row2)
  404. if idx2 != -1 {
  405. ws.SheetData.Row[idx2] = rowCopy
  406. } else {
  407. ws.SheetData.Row = append(ws.SheetData.Row, rowCopy)
  408. }
  409. }
  410. // checkRow provides a function to check and fill each column element for all
  411. // rows and make that is continuous in a worksheet of XML. For example:
  412. //
  413. // <row r="15" spans="1:22" x14ac:dyDescent="0.2">
  414. // <c r="A15" s="2" />
  415. // <c r="B15" s="2" />
  416. // <c r="F15" s="1" />
  417. // <c r="G15" s="1" />
  418. // </row>
  419. //
  420. // in this case, we should to change it to
  421. //
  422. // <row r="15" spans="1:22" x14ac:dyDescent="0.2">
  423. // <c r="A15" s="2" />
  424. // <c r="B15" s="2" />
  425. // <c r="C15" s="2" />
  426. // <c r="D15" s="2" />
  427. // <c r="E15" s="2" />
  428. // <c r="F15" s="1" />
  429. // <c r="G15" s="1" />
  430. // </row>
  431. //
  432. // Noteice: this method could be very slow for large spreadsheets (more than
  433. // 3000 rows one sheet).
  434. func checkRow(xlsx *xlsxWorksheet) {
  435. buffer := bytes.Buffer{}
  436. for k := range xlsx.SheetData.Row {
  437. lenCol := len(xlsx.SheetData.Row[k].C)
  438. if lenCol > 0 {
  439. endR := string(strings.Map(letterOnlyMapF, xlsx.SheetData.Row[k].C[lenCol-1].R))
  440. endRow, _ := strconv.Atoi(strings.Map(intOnlyMapF, xlsx.SheetData.Row[k].C[lenCol-1].R))
  441. endCol := TitleToNumber(endR) + 1
  442. if lenCol < endCol {
  443. oldRow := xlsx.SheetData.Row[k].C
  444. xlsx.SheetData.Row[k].C = xlsx.SheetData.Row[k].C[:0]
  445. var tmp []xlsxC
  446. for i := 0; i < endCol; i++ {
  447. buffer.WriteString(ToAlphaString(i))
  448. buffer.WriteString(strconv.Itoa(endRow))
  449. tmp = append(tmp, xlsxC{
  450. R: buffer.String(),
  451. })
  452. buffer.Reset()
  453. }
  454. xlsx.SheetData.Row[k].C = tmp
  455. for _, y := range oldRow {
  456. colAxis := TitleToNumber(string(strings.Map(letterOnlyMapF, y.R)))
  457. xlsx.SheetData.Row[k].C[colAxis] = y
  458. }
  459. }
  460. }
  461. }
  462. }
  463. // completeRow provides a function to check and fill each column element for a
  464. // single row and make that is continuous in a worksheet of XML by given row
  465. // index and axis.
  466. func completeRow(xlsx *xlsxWorksheet, row, cell int) {
  467. currentRows := len(xlsx.SheetData.Row)
  468. if currentRows > 1 {
  469. lastRow := xlsx.SheetData.Row[currentRows-1].R
  470. if lastRow >= row {
  471. row = lastRow
  472. }
  473. }
  474. for i := currentRows; i < row; i++ {
  475. xlsx.SheetData.Row = append(xlsx.SheetData.Row, xlsxRow{
  476. R: i + 1,
  477. })
  478. }
  479. buffer := bytes.Buffer{}
  480. for ii := currentRows; ii < row; ii++ {
  481. start := len(xlsx.SheetData.Row[ii].C)
  482. if start == 0 {
  483. for iii := start; iii < cell; iii++ {
  484. buffer.WriteString(ToAlphaString(iii))
  485. buffer.WriteString(strconv.Itoa(ii + 1))
  486. xlsx.SheetData.Row[ii].C = append(xlsx.SheetData.Row[ii].C, xlsxC{
  487. R: buffer.String(),
  488. })
  489. buffer.Reset()
  490. }
  491. }
  492. }
  493. }
  494. // convertRowHeightToPixels provides a function to convert the height of a
  495. // cell from user's units to pixels. If the height hasn't been set by the user
  496. // we use the default value. If the row is hidden it has a value of zero.
  497. func convertRowHeightToPixels(height float64) float64 {
  498. var pixels float64
  499. if height == 0 {
  500. return pixels
  501. }
  502. pixels = math.Ceil(4.0 / 3.0 * height)
  503. return pixels
  504. }