rows.go 13 KB

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