rows.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. package excelize
  2. import (
  3. "bytes"
  4. "encoding/xml"
  5. "math"
  6. "strconv"
  7. "strings"
  8. )
  9. // GetRows return all the rows in a sheet by given "sheet" + index. For now you
  10. // should use sheet_name like "sheet3" where "sheet" is a constant part and "3"
  11. // is a sheet number. For example, if sheet named as "SomeUniqueData" and it is
  12. // second if spreadsheet program interface - you should use "sheet2" here. For
  13. // example:
  14. //
  15. // index := xlsx.GetSheetIndex("Sheet2")
  16. // rows := xlsx.GetRows("sheet" + strconv.Itoa(index))
  17. // for _, row := range rows {
  18. // for _, colCell := range row {
  19. // fmt.Print(colCell, "\t")
  20. // }
  21. // fmt.Println()
  22. // }
  23. //
  24. func (f *File) GetRows(sheet string) [][]string {
  25. xlsx := f.workSheetReader(sheet)
  26. rows := [][]string{}
  27. name := "xl/worksheets/" + strings.ToLower(sheet) + ".xml"
  28. if xlsx != nil {
  29. output, _ := xml.Marshal(f.Sheet[name])
  30. f.saveFileList(name, replaceWorkSheetsRelationshipsNameSpace(string(output)))
  31. }
  32. decoder := xml.NewDecoder(strings.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(sheet)
  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(strings.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. // getTotalRowsCols provides a function to get total columns and rows in a
  70. // sheet.
  71. func (f *File) getTotalRowsCols(sheet string) (int, int) {
  72. name := "xl/worksheets/" + strings.ToLower(sheet) + ".xml"
  73. decoder := xml.NewDecoder(strings.NewReader(f.readXML(name)))
  74. var inElement string
  75. var r xlsxRow
  76. var tr, tc int
  77. for {
  78. token, _ := decoder.Token()
  79. if token == nil {
  80. break
  81. }
  82. switch startElement := token.(type) {
  83. case xml.StartElement:
  84. inElement = startElement.Name.Local
  85. if inElement == "row" {
  86. r = xlsxRow{}
  87. decoder.DecodeElement(&r, &startElement)
  88. tr = r.R
  89. for _, colCell := range r.C {
  90. col := TitleToNumber(strings.Map(letterOnlyMapF, colCell.R))
  91. if col > tc {
  92. tc = col
  93. }
  94. }
  95. }
  96. default:
  97. }
  98. }
  99. return tr, tc
  100. }
  101. // SetRowHeight provides a function to set the height of a single row.
  102. // For example:
  103. //
  104. // xlsx := excelize.NewFile()
  105. // xlsx.SetRowHeight("Sheet1", 0, 50)
  106. // err := xlsx.Save()
  107. // if err != nil {
  108. // fmt.Println(err)
  109. // os.Exit(1)
  110. // }
  111. //
  112. func (f *File) SetRowHeight(sheet string, rowIndex int, height float64) {
  113. xlsx := f.workSheetReader(sheet)
  114. rows := rowIndex + 1
  115. cells := 0
  116. completeRow(xlsx, rows, cells)
  117. xlsx.SheetData.Row[rowIndex].Ht = height
  118. xlsx.SheetData.Row[rowIndex].CustomHeight = true
  119. }
  120. // getRowHeight provides function to get row height in pixels by given sheet
  121. // name and row index.
  122. func (f *File) getRowHeight(sheet string, row int) int {
  123. xlsx := f.workSheetReader(sheet)
  124. for _, v := range xlsx.SheetData.Row {
  125. if v.R == row+1 && v.Ht != 0 {
  126. return int(convertRowHeightToPixels(v.Ht))
  127. }
  128. }
  129. // Optimisation for when the row heights haven't changed.
  130. return int(defaultRowHeightPixels)
  131. }
  132. // GetRowHeight provides function to get row height by given worksheet name and
  133. // row index.
  134. func (f *File) GetRowHeight(sheet string, row int) float64 {
  135. xlsx := f.workSheetReader(sheet)
  136. for _, v := range xlsx.SheetData.Row {
  137. if v.R == row+1 && v.Ht != 0 {
  138. return v.Ht
  139. }
  140. }
  141. // Optimisation for when the row heights haven't changed.
  142. return defaultRowHeightPixels
  143. }
  144. // sharedStringsReader provides function to get the pointer to the structure
  145. // after deserialization of xl/sharedStrings.xml.
  146. func (f *File) sharedStringsReader() *xlsxSST {
  147. if f.SharedStrings == nil {
  148. var sharedStrings xlsxSST
  149. xml.Unmarshal([]byte(f.readXML("xl/sharedStrings.xml")), &sharedStrings)
  150. f.SharedStrings = &sharedStrings
  151. }
  152. return f.SharedStrings
  153. }
  154. // getValueFrom return a value from a column/row cell, this function is inteded
  155. // to be used with for range on rows an argument with the xlsx opened file.
  156. func (xlsx *xlsxC) getValueFrom(f *File, d *xlsxSST) (string, error) {
  157. switch xlsx.T {
  158. case "s":
  159. xlsxSI := 0
  160. xlsxSI, _ = strconv.Atoi(xlsx.V)
  161. if len(d.SI[xlsxSI].R) > 0 {
  162. value := ""
  163. for _, v := range d.SI[xlsxSI].R {
  164. value += v.T
  165. }
  166. return value, nil
  167. }
  168. return f.formattedValue(xlsx.S, d.SI[xlsxSI].T), nil
  169. case "str":
  170. return f.formattedValue(xlsx.S, xlsx.V), nil
  171. default:
  172. return f.formattedValue(xlsx.S, xlsx.V), nil
  173. }
  174. }
  175. // SetRowVisible provides a function to set visible of a single row by given
  176. // worksheet index and row index. For example, hide row 3 in Sheet1:
  177. //
  178. // xlsx.SetRowVisible("Sheet1", 2, false)
  179. //
  180. func (f *File) SetRowVisible(sheet string, rowIndex int, visible bool) {
  181. xlsx := f.workSheetReader(sheet)
  182. rows := rowIndex + 1
  183. cells := 0
  184. completeRow(xlsx, rows, cells)
  185. if visible {
  186. xlsx.SheetData.Row[rowIndex].Hidden = false
  187. return
  188. }
  189. xlsx.SheetData.Row[rowIndex].Hidden = true
  190. }
  191. // GetRowVisible provides a function to get visible of a single row by given
  192. // worksheet index and row index. For example, get visible state of row 3 in
  193. // Sheet1:
  194. //
  195. // xlsx.GetRowVisible("Sheet1", 2)
  196. //
  197. func (f *File) GetRowVisible(sheet string, rowIndex int) bool {
  198. xlsx := f.workSheetReader(sheet)
  199. rows := rowIndex + 1
  200. cells := 0
  201. completeRow(xlsx, rows, cells)
  202. return !xlsx.SheetData.Row[rowIndex].Hidden
  203. }
  204. // RemoveRow provides function to remove single row by given worksheet index and
  205. // row index. For example, remove row 3 in Sheet1:
  206. //
  207. // xlsx.RemoveRow("Sheet1", 2)
  208. //
  209. func (f *File) RemoveRow(sheet string, row int) {
  210. if row < 0 {
  211. return
  212. }
  213. xlsx := f.workSheetReader(sheet)
  214. row++
  215. for i, r := range xlsx.SheetData.Row {
  216. if r.R != row {
  217. continue
  218. }
  219. xlsx.SheetData.Row = append(xlsx.SheetData.Row[:i], xlsx.SheetData.Row[i+1:]...)
  220. f.adjustHelper(sheet, -1, row, -1)
  221. return
  222. }
  223. }
  224. // InsertRow provides function to insert a new row before given row index. For
  225. // example, create a new row before row 3 in Sheet1:
  226. //
  227. // xlsx.InsertRow("Sheet1", 2)
  228. //
  229. func (f *File) InsertRow(sheet string, row int) {
  230. if row < 0 {
  231. return
  232. }
  233. row++
  234. f.adjustHelper(sheet, -1, row, 1)
  235. }
  236. // checkRow provides function to check and fill each column element for all rows
  237. // and make that is continuous in a worksheet of XML. For example:
  238. //
  239. // <row r="15" spans="1:22" x14ac:dyDescent="0.2">
  240. // <c r="A15" s="2" />
  241. // <c r="B15" s="2" />
  242. // <c r="F15" s="1" />
  243. // <c r="G15" s="1" />
  244. // </row>
  245. //
  246. // in this case, we should to change it to
  247. //
  248. // <row r="15" spans="1:22" x14ac:dyDescent="0.2">
  249. // <c r="A15" s="2" />
  250. // <c r="B15" s="2" />
  251. // <c r="C15" s="2" />
  252. // <c r="D15" s="2" />
  253. // <c r="E15" s="2" />
  254. // <c r="F15" s="1" />
  255. // <c r="G15" s="1" />
  256. // </row>
  257. //
  258. // Noteice: this method could be very slow for large spreadsheets (more than
  259. // 3000 rows one sheet).
  260. func checkRow(xlsx *xlsxWorksheet) {
  261. buffer := bytes.Buffer{}
  262. for k, v := range xlsx.SheetData.Row {
  263. lenCol := len(v.C)
  264. if lenCol < 1 {
  265. continue
  266. }
  267. endR := string(strings.Map(letterOnlyMapF, v.C[lenCol-1].R))
  268. endRow, _ := strconv.Atoi(strings.Map(intOnlyMapF, v.C[lenCol-1].R))
  269. endCol := TitleToNumber(endR) + 1
  270. if lenCol < endCol {
  271. oldRow := xlsx.SheetData.Row[k].C
  272. xlsx.SheetData.Row[k].C = xlsx.SheetData.Row[k].C[:0]
  273. tmp := []xlsxC{}
  274. for i := 0; i <= endCol; i++ {
  275. buffer.WriteString(ToAlphaString(i))
  276. buffer.WriteString(strconv.Itoa(endRow))
  277. tmp = append(tmp, xlsxC{
  278. R: buffer.String(),
  279. })
  280. buffer.Reset()
  281. }
  282. xlsx.SheetData.Row[k].C = tmp
  283. for _, y := range oldRow {
  284. colAxis := TitleToNumber(string(strings.Map(letterOnlyMapF, y.R)))
  285. xlsx.SheetData.Row[k].C[colAxis] = y
  286. }
  287. }
  288. }
  289. }
  290. // completeRow provides function to check and fill each column element for a
  291. // single row and make that is continuous in a worksheet of XML by given row
  292. // index and axis.
  293. func completeRow(xlsx *xlsxWorksheet, row, cell int) {
  294. currentRows := len(xlsx.SheetData.Row)
  295. if currentRows > 1 {
  296. lastRow := xlsx.SheetData.Row[currentRows-1].R
  297. if lastRow >= row {
  298. row = lastRow
  299. }
  300. }
  301. for i := currentRows; i < row; i++ {
  302. xlsx.SheetData.Row = append(xlsx.SheetData.Row, xlsxRow{
  303. R: i + 1,
  304. })
  305. }
  306. buffer := bytes.Buffer{}
  307. for ii := currentRows; ii < row; ii++ {
  308. start := len(xlsx.SheetData.Row[ii].C)
  309. if start == 0 {
  310. for iii := start; iii < cell; iii++ {
  311. buffer.WriteString(ToAlphaString(iii))
  312. buffer.WriteString(strconv.Itoa(ii + 1))
  313. xlsx.SheetData.Row[ii].C = append(xlsx.SheetData.Row[ii].C, xlsxC{
  314. R: buffer.String(),
  315. })
  316. buffer.Reset()
  317. }
  318. }
  319. }
  320. }
  321. // convertRowHeightToPixels provides function to convert the height of a cell
  322. // from user's units to pixels. If the height hasn't been set by the user we use
  323. // the default value. If the row is hidden it has a value of zero.
  324. func convertRowHeightToPixels(height float64) float64 {
  325. var pixels float64
  326. if height == 0 {
  327. return pixels
  328. }
  329. pixels = math.Ceil(4.0 / 3.0 * height)
  330. return pixels
  331. }