rows.go 13 KB

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