rows.go 14 KB

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