rows.go 13 KB

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