rows.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  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. func (f *File) RemoveRow(sheet string, row int) {
  325. if row < 0 {
  326. return
  327. }
  328. xlsx := f.workSheetReader(sheet)
  329. row++
  330. for i, r := range xlsx.SheetData.Row {
  331. if r.R == row {
  332. xlsx.SheetData.Row = append(xlsx.SheetData.Row[:i], xlsx.SheetData.Row[i+1:]...)
  333. f.adjustHelper(sheet, -1, row, -1)
  334. return
  335. }
  336. }
  337. }
  338. // InsertRow provides a function to insert a new row after given row index.
  339. // For example, create a new row before row 3 in Sheet1:
  340. //
  341. // xlsx.InsertRow("Sheet1", 2)
  342. //
  343. func (f *File) InsertRow(sheet string, row int) {
  344. if row < 0 {
  345. return
  346. }
  347. row++
  348. f.adjustHelper(sheet, -1, row, 1)
  349. }
  350. // DuplicateRow inserts a copy of specified row below specified
  351. //
  352. // xlsx.DuplicateRow("Sheet1", 2)
  353. //
  354. func (f *File) DuplicateRow(sheet string, row int) {
  355. if row < 0 {
  356. return
  357. }
  358. row2 := row + 1
  359. f.adjustHelper(sheet, -1, row2, 1)
  360. xlsx := f.workSheetReader(sheet)
  361. idx := -1
  362. idx2 := -1
  363. for i, r := range xlsx.SheetData.Row {
  364. if r.R == row {
  365. idx = i
  366. } else if r.R == row2 {
  367. idx2 = i
  368. }
  369. if idx != -1 && idx2 != -1 {
  370. break
  371. }
  372. }
  373. if idx == -1 || (idx2 == -1 && len(xlsx.SheetData.Row) >= row2) {
  374. return
  375. }
  376. rowData := xlsx.SheetData.Row[idx]
  377. cols := make([]xlsxC, 0, len(rowData.C))
  378. rowData.C = append(cols, rowData.C...)
  379. f.ajustSingleRowDimensions(&rowData, 1)
  380. if idx2 != -1 {
  381. xlsx.SheetData.Row[idx2] = rowData
  382. } else {
  383. xlsx.SheetData.Row = append(xlsx.SheetData.Row, rowData)
  384. }
  385. }
  386. // checkRow provides a function to check and fill each column element for all
  387. // rows and make that is continuous in a worksheet of XML. For example:
  388. //
  389. // <row r="15" spans="1:22" x14ac:dyDescent="0.2">
  390. // <c r="A15" s="2" />
  391. // <c r="B15" s="2" />
  392. // <c r="F15" s="1" />
  393. // <c r="G15" s="1" />
  394. // </row>
  395. //
  396. // in this case, we should to change it to
  397. //
  398. // <row r="15" spans="1:22" x14ac:dyDescent="0.2">
  399. // <c r="A15" s="2" />
  400. // <c r="B15" s="2" />
  401. // <c r="C15" s="2" />
  402. // <c r="D15" s="2" />
  403. // <c r="E15" s="2" />
  404. // <c r="F15" s="1" />
  405. // <c r="G15" s="1" />
  406. // </row>
  407. //
  408. // Noteice: this method could be very slow for large spreadsheets (more than
  409. // 3000 rows one sheet).
  410. func checkRow(xlsx *xlsxWorksheet) {
  411. buffer := bytes.Buffer{}
  412. for k := range xlsx.SheetData.Row {
  413. lenCol := len(xlsx.SheetData.Row[k].C)
  414. if lenCol > 0 {
  415. endR := string(strings.Map(letterOnlyMapF, xlsx.SheetData.Row[k].C[lenCol-1].R))
  416. endRow, _ := strconv.Atoi(strings.Map(intOnlyMapF, xlsx.SheetData.Row[k].C[lenCol-1].R))
  417. endCol := TitleToNumber(endR) + 1
  418. if lenCol < endCol {
  419. oldRow := xlsx.SheetData.Row[k].C
  420. xlsx.SheetData.Row[k].C = xlsx.SheetData.Row[k].C[:0]
  421. tmp := []xlsxC{}
  422. for i := 0; i < endCol; i++ {
  423. buffer.WriteString(ToAlphaString(i))
  424. buffer.WriteString(strconv.Itoa(endRow))
  425. tmp = append(tmp, xlsxC{
  426. R: buffer.String(),
  427. })
  428. buffer.Reset()
  429. }
  430. xlsx.SheetData.Row[k].C = tmp
  431. for _, y := range oldRow {
  432. colAxis := TitleToNumber(string(strings.Map(letterOnlyMapF, y.R)))
  433. xlsx.SheetData.Row[k].C[colAxis] = y
  434. }
  435. }
  436. }
  437. }
  438. }
  439. // completeRow provides a function to check and fill each column element for a
  440. // single row and make that is continuous in a worksheet of XML by given row
  441. // index and axis.
  442. func completeRow(xlsx *xlsxWorksheet, row, cell int) {
  443. currentRows := len(xlsx.SheetData.Row)
  444. if currentRows > 1 {
  445. lastRow := xlsx.SheetData.Row[currentRows-1].R
  446. if lastRow >= row {
  447. row = lastRow
  448. }
  449. }
  450. for i := currentRows; i < row; i++ {
  451. xlsx.SheetData.Row = append(xlsx.SheetData.Row, xlsxRow{
  452. R: i + 1,
  453. })
  454. }
  455. buffer := bytes.Buffer{}
  456. for ii := currentRows; ii < row; ii++ {
  457. start := len(xlsx.SheetData.Row[ii].C)
  458. if start == 0 {
  459. for iii := start; iii < cell; iii++ {
  460. buffer.WriteString(ToAlphaString(iii))
  461. buffer.WriteString(strconv.Itoa(ii + 1))
  462. xlsx.SheetData.Row[ii].C = append(xlsx.SheetData.Row[ii].C, xlsxC{
  463. R: buffer.String(),
  464. })
  465. buffer.Reset()
  466. }
  467. }
  468. }
  469. }
  470. // convertRowHeightToPixels provides a function to convert the height of a
  471. // cell from user's units to pixels. If the height hasn't been set by the user
  472. // we use the default value. If the row is hidden it has a value of zero.
  473. func convertRowHeightToPixels(height float64) float64 {
  474. var pixels float64
  475. if height == 0 {
  476. return pixels
  477. }
  478. pixels = math.Ceil(4.0 / 3.0 * height)
  479. return pixels
  480. }