rows.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  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. )
  18. // GetRows return all the rows in a sheet by given worksheet name (case
  19. // sensitive). For example:
  20. //
  21. // for _, row := range xlsx.GetRows("Sheet1") {
  22. // for _, colCell := range row {
  23. // fmt.Print(colCell, "\t")
  24. // }
  25. // fmt.Println()
  26. // }
  27. //
  28. func (f *File) GetRows(sheet string) [][]string {
  29. name, ok := f.sheetMap[trimSheetName(sheet)]
  30. if !ok {
  31. return nil
  32. }
  33. xlsx := f.workSheetReader(sheet)
  34. if xlsx != nil {
  35. output, _ := xml.Marshal(f.Sheet[name])
  36. f.saveFileList(name, replaceWorkSheetsRelationshipsNameSpaceBytes(output))
  37. }
  38. xml.NewDecoder(bytes.NewReader(f.readXML(name)))
  39. d := f.sharedStringsReader()
  40. var (
  41. inElement string
  42. rowData xlsxRow
  43. )
  44. rowCount, colCount := f.getTotalRowsCols(name)
  45. rows := make([][]string, rowCount)
  46. for i := range rows {
  47. rows[i] = make([]string, colCount+1)
  48. }
  49. var row int
  50. decoder := xml.NewDecoder(bytes.NewReader(f.readXML(name)))
  51. for {
  52. token, _ := decoder.Token()
  53. if token == nil {
  54. break
  55. }
  56. switch startElement := token.(type) {
  57. case xml.StartElement:
  58. inElement = startElement.Name.Local
  59. if inElement == "row" {
  60. rowData = xlsxRow{}
  61. _ = decoder.DecodeElement(&rowData, &startElement)
  62. cr := rowData.R - 1
  63. for _, colCell := range rowData.C {
  64. col, _ := MustCellNameToCoordinates(colCell.R)
  65. val, _ := colCell.getValueFrom(f, d)
  66. rows[cr][col-1] = val
  67. if val != "" {
  68. row = rowData.R
  69. }
  70. }
  71. }
  72. default:
  73. }
  74. }
  75. return rows[:row]
  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. columns := make([]string, len(r.C))
  117. for _, colCell := range r.C {
  118. col, _ := MustCellNameToCoordinates(colCell.R)
  119. val, _ := colCell.getValueFrom(rows.f, d)
  120. columns[col-1] = val
  121. }
  122. return columns
  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, _ := MustCellNameToCoordinates(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. if row < 1 {
  194. panic(newInvalidRowNumberError(row)) // Fail fast to avoid possible future side effects!
  195. }
  196. xlsx := f.workSheetReader(sheet)
  197. prepareSheetXML(xlsx, 0, row)
  198. rowIdx := row - 1
  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. if row < 1 {
  221. panic(newInvalidRowNumberError(row)) // Fail fast to avoid possible future side effects!
  222. }
  223. xlsx := f.workSheetReader(sheet)
  224. if row > len(xlsx.SheetData.Row) {
  225. return defaultRowHeightPixels // it will be better to use 0, but we take care with BC
  226. }
  227. for _, v := range xlsx.SheetData.Row {
  228. if v.R == row && v.Ht != 0 {
  229. return v.Ht
  230. }
  231. }
  232. // Optimisation for when the row heights haven't changed.
  233. return defaultRowHeightPixels
  234. }
  235. // sharedStringsReader provides a function to get the pointer to the structure
  236. // after deserialization of xl/sharedStrings.xml.
  237. func (f *File) sharedStringsReader() *xlsxSST {
  238. if f.SharedStrings == nil {
  239. var sharedStrings xlsxSST
  240. ss := f.readXML("xl/sharedStrings.xml")
  241. if len(ss) == 0 {
  242. ss = f.readXML("xl/SharedStrings.xml")
  243. }
  244. _ = xml.Unmarshal(namespaceStrictToTransitional(ss), &sharedStrings)
  245. f.SharedStrings = &sharedStrings
  246. }
  247. return f.SharedStrings
  248. }
  249. // getValueFrom return a value from a column/row cell, this function is
  250. // inteded to be used with for range on rows an argument with the xlsx opened
  251. // file.
  252. func (xlsx *xlsxC) getValueFrom(f *File, d *xlsxSST) (string, error) {
  253. switch xlsx.T {
  254. case "s":
  255. xlsxSI := 0
  256. xlsxSI, _ = strconv.Atoi(xlsx.V)
  257. if len(d.SI[xlsxSI].R) > 0 {
  258. value := ""
  259. for _, v := range d.SI[xlsxSI].R {
  260. value += v.T
  261. }
  262. return value, nil
  263. }
  264. return f.formattedValue(xlsx.S, d.SI[xlsxSI].T), nil
  265. case "str":
  266. return f.formattedValue(xlsx.S, xlsx.V), nil
  267. case "inlineStr":
  268. return f.formattedValue(xlsx.S, xlsx.IS.T), nil
  269. default:
  270. return f.formattedValue(xlsx.S, xlsx.V), nil
  271. }
  272. }
  273. // SetRowVisible provides a function to set visible of a single row by given
  274. // worksheet name and Excel row number. For example, hide row 2 in Sheet1:
  275. //
  276. // xlsx.SetRowVisible("Sheet1", 2, false)
  277. //
  278. func (f *File) SetRowVisible(sheet string, row int, visible bool) {
  279. if row < 1 {
  280. panic(newInvalidRowNumberError(row)) // Fail fast to avoid possible future side effects!
  281. }
  282. xlsx := f.workSheetReader(sheet)
  283. prepareSheetXML(xlsx, 0, row)
  284. xlsx.SheetData.Row[row-1].Hidden = !visible
  285. }
  286. // GetRowVisible provides a function to get visible of a single row by given
  287. // worksheet name and Excel row number. For example, get visible state of row
  288. // 2 in Sheet1:
  289. //
  290. // xlsx.GetRowVisible("Sheet1", 2)
  291. //
  292. func (f *File) GetRowVisible(sheet string, row int) bool {
  293. if row < 1 {
  294. panic(newInvalidRowNumberError(row)) // Fail fast to avoid possible future side effects!
  295. }
  296. xlsx := f.workSheetReader(sheet)
  297. if row > len(xlsx.SheetData.Row) {
  298. return false
  299. }
  300. return !xlsx.SheetData.Row[row-1].Hidden
  301. }
  302. // SetRowOutlineLevel provides a function to set outline level number of a
  303. // single row by given worksheet name and Excel row number. For example,
  304. // outline row 2 in Sheet1 to level 1:
  305. //
  306. // xlsx.SetRowOutlineLevel("Sheet1", 2, 1)
  307. //
  308. func (f *File) SetRowOutlineLevel(sheet string, row int, level uint8) {
  309. if row < 1 {
  310. panic(newInvalidRowNumberError(row)) // Fail fast to avoid possible future side effects!
  311. }
  312. xlsx := f.workSheetReader(sheet)
  313. prepareSheetXML(xlsx, 0, row)
  314. xlsx.SheetData.Row[row-1].OutlineLevel = level
  315. }
  316. // GetRowOutlineLevel provides a function to get outline level number of a
  317. // single row by given worksheet name and Excel row number. For example, get
  318. // outline number of row 2 in Sheet1:
  319. //
  320. // xlsx.GetRowOutlineLevel("Sheet1", 2)
  321. //
  322. func (f *File) GetRowOutlineLevel(sheet string, row int) uint8 {
  323. if row < 1 {
  324. panic(newInvalidRowNumberError(row)) // Fail fast to avoid possible future side effects!
  325. }
  326. xlsx := f.workSheetReader(sheet)
  327. if row > len(xlsx.SheetData.Row) {
  328. return 0
  329. }
  330. return xlsx.SheetData.Row[row-1].OutlineLevel
  331. }
  332. // RemoveRow provides a function to remove single row by given worksheet name
  333. // and Excel row number. For example, remove row 3 in Sheet1:
  334. //
  335. // xlsx.RemoveRow("Sheet1", 3)
  336. //
  337. // Use this method with caution, which will affect changes in references such
  338. // as formulas, charts, and so on. If there is any referenced value of the
  339. // worksheet, it will cause a file error when you open it. The excelize only
  340. // partially updates these references currently.
  341. func (f *File) RemoveRow(sheet string, row int) {
  342. if row < 1 {
  343. panic(newInvalidRowNumberError(row)) // Fail fast to avoid possible future side effects!
  344. }
  345. xlsx := f.workSheetReader(sheet)
  346. if row > len(xlsx.SheetData.Row) {
  347. return
  348. }
  349. for rowIdx := range xlsx.SheetData.Row {
  350. if xlsx.SheetData.Row[rowIdx].R == row {
  351. xlsx.SheetData.Row = append(xlsx.SheetData.Row[:rowIdx],
  352. xlsx.SheetData.Row[rowIdx+1:]...)[:len(xlsx.SheetData.Row)-1]
  353. f.adjustHelper(sheet, rows, row, -1)
  354. return
  355. }
  356. }
  357. }
  358. // InsertRow provides a function to insert a new row after given Excel row
  359. // number starting from 1. For example, create a new row before row 3 in
  360. // Sheet1:
  361. //
  362. // xlsx.InsertRow("Sheet1", 3)
  363. //
  364. func (f *File) InsertRow(sheet string, row int) {
  365. if row < 1 {
  366. panic(newInvalidRowNumberError(row)) // Fail fast to avoid possible future side effects!
  367. }
  368. f.adjustHelper(sheet, rows, row, 1)
  369. }
  370. // DuplicateRow inserts a copy of specified row (by it Excel row number) below
  371. //
  372. // xlsx.DuplicateRow("Sheet1", 2)
  373. //
  374. // Use this method with caution, which will affect changes in references such
  375. // as formulas, charts, and so on. If there is any referenced value of the
  376. // worksheet, it will cause a file error when you open it. The excelize only
  377. // partially updates these references currently.
  378. func (f *File) DuplicateRow(sheet string, row int) {
  379. f.DuplicateRowTo(sheet, row, row+1)
  380. }
  381. // DuplicateRowTo inserts a copy of specified row by it Excel number
  382. // to specified row position moving down exists rows after target position
  383. //
  384. // xlsx.DuplicateRowTo("Sheet1", 2, 7)
  385. //
  386. // Use this method with caution, which will affect changes in references such
  387. // as formulas, charts, and so on. If there is any referenced value of the
  388. // worksheet, it will cause a file error when you open it. The excelize only
  389. // partially updates these references currently.
  390. func (f *File) DuplicateRowTo(sheet string, row, row2 int) {
  391. if row < 1 {
  392. panic(newInvalidRowNumberError(row)) // Fail fast to avoid possible future side effects!
  393. }
  394. xlsx := f.workSheetReader(sheet)
  395. if row > len(xlsx.SheetData.Row) || row2 < 1 || row == row2 {
  396. return
  397. }
  398. var ok bool
  399. var rowCopy xlsxRow
  400. for i, r := range xlsx.SheetData.Row {
  401. if r.R == row {
  402. rowCopy = xlsx.SheetData.Row[i]
  403. ok = true
  404. break
  405. }
  406. }
  407. if !ok {
  408. return
  409. }
  410. f.adjustHelper(sheet, rows, row2, 1)
  411. idx2 := -1
  412. for i, r := range xlsx.SheetData.Row {
  413. if r.R == row2 {
  414. idx2 = i
  415. break
  416. }
  417. }
  418. if idx2 == -1 && len(xlsx.SheetData.Row) >= row2 {
  419. return
  420. }
  421. rowCopy.C = append(make([]xlsxC, 0, len(rowCopy.C)), rowCopy.C...)
  422. f.ajustSingleRowDimensions(&rowCopy, row2)
  423. if idx2 != -1 {
  424. xlsx.SheetData.Row[idx2] = rowCopy
  425. } else {
  426. xlsx.SheetData.Row = append(xlsx.SheetData.Row, rowCopy)
  427. }
  428. }
  429. // checkRow provides a function to check and fill each column element for all
  430. // rows and make that is continuous in a worksheet of XML. For example:
  431. //
  432. // <row r="15" spans="1:22" x14ac:dyDescent="0.2">
  433. // <c r="A15" s="2" />
  434. // <c r="B15" s="2" />
  435. // <c r="F15" s="1" />
  436. // <c r="G15" s="1" />
  437. // </row>
  438. //
  439. // in this case, we should to change it to
  440. //
  441. // <row r="15" spans="1:22" x14ac:dyDescent="0.2">
  442. // <c r="A15" s="2" />
  443. // <c r="B15" s="2" />
  444. // <c r="C15" s="2" />
  445. // <c r="D15" s="2" />
  446. // <c r="E15" s="2" />
  447. // <c r="F15" s="1" />
  448. // <c r="G15" s="1" />
  449. // </row>
  450. //
  451. // Noteice: this method could be very slow for large spreadsheets (more than
  452. // 3000 rows one sheet).
  453. func checkRow(xlsx *xlsxWorksheet) {
  454. for rowIdx := range xlsx.SheetData.Row {
  455. rowData := &xlsx.SheetData.Row[rowIdx]
  456. colCount := len(rowData.C)
  457. if colCount == 0 {
  458. continue
  459. }
  460. lastCol, _ := MustCellNameToCoordinates(rowData.C[colCount-1].R)
  461. if colCount < lastCol {
  462. oldList := rowData.C
  463. newlist := make([]xlsxC, 0, lastCol)
  464. rowData.C = xlsx.SheetData.Row[rowIdx].C[:0]
  465. for colIdx := 0; colIdx < lastCol; colIdx++ {
  466. newlist = append(newlist, xlsxC{R: MustCoordinatesToCellName(colIdx+1, rowIdx+1)})
  467. }
  468. rowData.C = newlist
  469. for colIdx := range oldList {
  470. colData := &oldList[colIdx]
  471. colNum, _ := MustCellNameToCoordinates(colData.R)
  472. xlsx.SheetData.Row[rowIdx].C[colNum-1] = *colData
  473. }
  474. }
  475. }
  476. }
  477. // convertRowHeightToPixels provides a function to convert the height of a
  478. // cell from user's units to pixels. If the height hasn't been set by the user
  479. // we use the default value. If the row is hidden it has a value of zero.
  480. func convertRowHeightToPixels(height float64) float64 {
  481. var pixels float64
  482. if height == 0 {
  483. return pixels
  484. }
  485. pixels = math.Ceil(4.0 / 3.0 * height)
  486. return pixels
  487. }