rows.go 13 KB

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