rows.go 12 KB

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