rows.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  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. "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. output, _ := xml.Marshal(f.Sheet[name])
  105. f.saveFileList(name, replaceWorkSheetsRelationshipsNameSpaceBytes(output))
  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. if len(d.SI[xlsxSI].R) > 0 {
  190. value := ""
  191. for _, v := range d.SI[xlsxSI].R {
  192. value += v.T
  193. }
  194. return value, nil
  195. }
  196. return f.formattedValue(xlsx.S, d.SI[xlsxSI].T), nil
  197. case "str":
  198. return f.formattedValue(xlsx.S, xlsx.V), nil
  199. case "inlineStr":
  200. return f.formattedValue(xlsx.S, xlsx.IS.T), nil
  201. default:
  202. return f.formattedValue(xlsx.S, xlsx.V), nil
  203. }
  204. }
  205. // SetRowVisible provides a function to set visible of a single row by given
  206. // worksheet name and Excel row number. For example, hide row 2 in Sheet1:
  207. //
  208. // err := f.SetRowVisible("Sheet1", 2, false)
  209. //
  210. func (f *File) SetRowVisible(sheet string, row int, visible bool) error {
  211. if row < 1 {
  212. return newInvalidRowNumberError(row)
  213. }
  214. xlsx, err := f.workSheetReader(sheet)
  215. if err != nil {
  216. return err
  217. }
  218. prepareSheetXML(xlsx, 0, row)
  219. xlsx.SheetData.Row[row-1].Hidden = !visible
  220. return nil
  221. }
  222. // GetRowVisible provides a function to get visible of a single row by given
  223. // worksheet name and Excel row number. For example, get visible state of row
  224. // 2 in Sheet1:
  225. //
  226. // visible, err := f.GetRowVisible("Sheet1", 2)
  227. //
  228. func (f *File) GetRowVisible(sheet string, row int) (bool, error) {
  229. if row < 1 {
  230. return false, newInvalidRowNumberError(row)
  231. }
  232. xlsx, err := f.workSheetReader(sheet)
  233. if err != nil {
  234. return false, err
  235. }
  236. if row > len(xlsx.SheetData.Row) {
  237. return false, nil
  238. }
  239. return !xlsx.SheetData.Row[row-1].Hidden, nil
  240. }
  241. // SetRowOutlineLevel provides a function to set outline level number of a
  242. // single row by given worksheet name and Excel row number. For example,
  243. // outline row 2 in Sheet1 to level 1:
  244. //
  245. // err := f.SetRowOutlineLevel("Sheet1", 2, 1)
  246. //
  247. func (f *File) SetRowOutlineLevel(sheet string, row int, level uint8) error {
  248. if row < 1 {
  249. return newInvalidRowNumberError(row)
  250. }
  251. xlsx, err := f.workSheetReader(sheet)
  252. if err != nil {
  253. return err
  254. }
  255. prepareSheetXML(xlsx, 0, row)
  256. xlsx.SheetData.Row[row-1].OutlineLevel = level
  257. return nil
  258. }
  259. // GetRowOutlineLevel provides a function to get outline level number of a
  260. // single row by given worksheet name and Excel row number. For example, get
  261. // outline number of row 2 in Sheet1:
  262. //
  263. // level, err := f.GetRowOutlineLevel("Sheet1", 2)
  264. //
  265. func (f *File) GetRowOutlineLevel(sheet string, row int) (uint8, error) {
  266. if row < 1 {
  267. return 0, newInvalidRowNumberError(row)
  268. }
  269. xlsx, err := f.workSheetReader(sheet)
  270. if err != nil {
  271. return 0, err
  272. }
  273. if row > len(xlsx.SheetData.Row) {
  274. return 0, nil
  275. }
  276. return xlsx.SheetData.Row[row-1].OutlineLevel, nil
  277. }
  278. // RemoveRow provides a function to remove single row by given worksheet name
  279. // and Excel row number. For example, remove row 3 in Sheet1:
  280. //
  281. // err := f.RemoveRow("Sheet1", 3)
  282. //
  283. // Use this method with caution, which will affect changes in references such
  284. // as formulas, charts, and so on. If there is any referenced value of the
  285. // worksheet, it will cause a file error when you open it. The excelize only
  286. // partially updates these references currently.
  287. func (f *File) RemoveRow(sheet string, row int) error {
  288. if row < 1 {
  289. return newInvalidRowNumberError(row)
  290. }
  291. xlsx, err := f.workSheetReader(sheet)
  292. if err != nil {
  293. return err
  294. }
  295. if row > len(xlsx.SheetData.Row) {
  296. return f.adjustHelper(sheet, rows, row, -1)
  297. }
  298. for rowIdx := range xlsx.SheetData.Row {
  299. if xlsx.SheetData.Row[rowIdx].R == row {
  300. xlsx.SheetData.Row = append(xlsx.SheetData.Row[:rowIdx],
  301. xlsx.SheetData.Row[rowIdx+1:]...)[:len(xlsx.SheetData.Row)-1]
  302. return f.adjustHelper(sheet, rows, row, -1)
  303. }
  304. }
  305. return nil
  306. }
  307. // InsertRow provides a function to insert a new row after given Excel row
  308. // number starting from 1. For example, create a new row before row 3 in
  309. // Sheet1:
  310. //
  311. // err := f.InsertRow("Sheet1", 3)
  312. //
  313. // Use this method with caution, which will affect changes in references such
  314. // as formulas, charts, and so on. If there is any referenced value of the
  315. // worksheet, it will cause a file error when you open it. The excelize only
  316. // partially updates these references currently.
  317. func (f *File) InsertRow(sheet string, row int) error {
  318. if row < 1 {
  319. return newInvalidRowNumberError(row)
  320. }
  321. return f.adjustHelper(sheet, rows, row, 1)
  322. }
  323. // DuplicateRow inserts a copy of specified row (by its Excel row number) below
  324. //
  325. // err := f.DuplicateRow("Sheet1", 2)
  326. //
  327. // Use this method with caution, which will affect changes in references such
  328. // as formulas, charts, and so on. If there is any referenced value of the
  329. // worksheet, it will cause a file error when you open it. The excelize only
  330. // partially updates these references currently.
  331. func (f *File) DuplicateRow(sheet string, row int) error {
  332. return f.DuplicateRowTo(sheet, row, row+1)
  333. }
  334. // DuplicateRowTo inserts a copy of specified row by it Excel number
  335. // to specified row position moving down exists rows after target position
  336. //
  337. // err := f.DuplicateRowTo("Sheet1", 2, 7)
  338. //
  339. // Use this method with caution, which will affect changes in references such
  340. // as formulas, charts, and so on. If there is any referenced value of the
  341. // worksheet, it will cause a file error when you open it. The excelize only
  342. // partially updates these references currently.
  343. func (f *File) DuplicateRowTo(sheet string, row, row2 int) error {
  344. if row < 1 {
  345. return newInvalidRowNumberError(row)
  346. }
  347. xlsx, err := f.workSheetReader(sheet)
  348. if err != nil {
  349. return err
  350. }
  351. if row > len(xlsx.SheetData.Row) || row2 < 1 || row == row2 {
  352. return nil
  353. }
  354. var ok bool
  355. var rowCopy xlsxRow
  356. for i, r := range xlsx.SheetData.Row {
  357. if r.R == row {
  358. rowCopy = xlsx.SheetData.Row[i]
  359. ok = true
  360. break
  361. }
  362. }
  363. if !ok {
  364. return nil
  365. }
  366. if err := f.adjustHelper(sheet, rows, row2, 1); err != nil {
  367. return err
  368. }
  369. idx2 := -1
  370. for i, r := range xlsx.SheetData.Row {
  371. if r.R == row2 {
  372. idx2 = i
  373. break
  374. }
  375. }
  376. if idx2 == -1 && len(xlsx.SheetData.Row) >= row2 {
  377. return nil
  378. }
  379. rowCopy.C = append(make([]xlsxC, 0, len(rowCopy.C)), rowCopy.C...)
  380. f.ajustSingleRowDimensions(&rowCopy, row2)
  381. if idx2 != -1 {
  382. xlsx.SheetData.Row[idx2] = rowCopy
  383. } else {
  384. xlsx.SheetData.Row = append(xlsx.SheetData.Row, rowCopy)
  385. }
  386. return nil
  387. }
  388. // checkRow provides a function to check and fill each column element for all
  389. // rows and make that is continuous in a worksheet of XML. For example:
  390. //
  391. // <row r="15" spans="1:22" x14ac:dyDescent="0.2">
  392. // <c r="A15" s="2" />
  393. // <c r="B15" s="2" />
  394. // <c r="F15" s="1" />
  395. // <c r="G15" s="1" />
  396. // </row>
  397. //
  398. // in this case, we should to change it to
  399. //
  400. // <row r="15" spans="1:22" x14ac:dyDescent="0.2">
  401. // <c r="A15" s="2" />
  402. // <c r="B15" s="2" />
  403. // <c r="C15" s="2" />
  404. // <c r="D15" s="2" />
  405. // <c r="E15" s="2" />
  406. // <c r="F15" s="1" />
  407. // <c r="G15" s="1" />
  408. // </row>
  409. //
  410. // Noteice: this method could be very slow for large spreadsheets (more than
  411. // 3000 rows one sheet).
  412. func checkRow(xlsx *xlsxWorksheet) error {
  413. for rowIdx := range xlsx.SheetData.Row {
  414. rowData := &xlsx.SheetData.Row[rowIdx]
  415. colCount := len(rowData.C)
  416. if colCount == 0 {
  417. continue
  418. }
  419. lastCol, _, err := CellNameToCoordinates(rowData.C[colCount-1].R)
  420. if err != nil {
  421. return err
  422. }
  423. if colCount < lastCol {
  424. oldList := rowData.C
  425. newlist := make([]xlsxC, 0, lastCol)
  426. rowData.C = xlsx.SheetData.Row[rowIdx].C[:0]
  427. for colIdx := 0; colIdx < lastCol; colIdx++ {
  428. cellName, err := CoordinatesToCellName(colIdx+1, rowIdx+1)
  429. if err != nil {
  430. return err
  431. }
  432. newlist = append(newlist, xlsxC{R: cellName})
  433. }
  434. rowData.C = newlist
  435. for colIdx := range oldList {
  436. colData := &oldList[colIdx]
  437. colNum, _, err := CellNameToCoordinates(colData.R)
  438. if err != nil {
  439. return err
  440. }
  441. xlsx.SheetData.Row[rowIdx].C[colNum-1] = *colData
  442. }
  443. }
  444. }
  445. return nil
  446. }
  447. // convertRowHeightToPixels provides a function to convert the height of a
  448. // cell from user's units to pixels. If the height hasn't been set by the user
  449. // we use the default value. If the row is hidden it has a value of zero.
  450. func convertRowHeightToPixels(height float64) float64 {
  451. var pixels float64
  452. if height == 0 {
  453. return pixels
  454. }
  455. pixels = math.Ceil(4.0 / 3.0 * height)
  456. return pixels
  457. }