rows.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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 worksheet name (case
  10. // sensitive). For example:
  11. //
  12. // for _, row := range xlsx.GetRows("Sheet1") {
  13. // for _, colCell := range row {
  14. // fmt.Print(colCell, "\t")
  15. // }
  16. // fmt.Println()
  17. // }
  18. //
  19. func (f *File) GetRows(sheet string) [][]string {
  20. xlsx := f.workSheetReader(sheet)
  21. rows := [][]string{}
  22. name, ok := f.sheetMap[trimSheetName(sheet)]
  23. if !ok {
  24. return rows
  25. }
  26. if xlsx != nil {
  27. output, _ := xml.Marshal(f.Sheet[name])
  28. f.saveFileList(name, replaceWorkSheetsRelationshipsNameSpace(string(output)))
  29. }
  30. decoder := xml.NewDecoder(strings.NewReader(f.readXML(name)))
  31. d := f.sharedStringsReader()
  32. var inElement string
  33. var r xlsxRow
  34. var row []string
  35. tr, tc := f.getTotalRowsCols(name)
  36. for i := 0; i < tr; i++ {
  37. row = []string{}
  38. for j := 0; j <= tc; j++ {
  39. row = append(row, "")
  40. }
  41. rows = append(rows, row)
  42. }
  43. decoder = xml.NewDecoder(strings.NewReader(f.readXML(name)))
  44. for {
  45. token, _ := decoder.Token()
  46. if token == nil {
  47. break
  48. }
  49. switch startElement := token.(type) {
  50. case xml.StartElement:
  51. inElement = startElement.Name.Local
  52. if inElement == "row" {
  53. r = xlsxRow{}
  54. decoder.DecodeElement(&r, &startElement)
  55. cr := r.R - 1
  56. for _, colCell := range r.C {
  57. c := TitleToNumber(strings.Map(letterOnlyMapF, colCell.R))
  58. val, _ := colCell.getValueFrom(f, d)
  59. rows[cr][c] = val
  60. }
  61. }
  62. default:
  63. }
  64. }
  65. return rows
  66. }
  67. // getTotalRowsCols provides a function to get total columns and rows in a
  68. // worksheet.
  69. func (f *File) getTotalRowsCols(name string) (int, int) {
  70. decoder := xml.NewDecoder(strings.NewReader(f.readXML(name)))
  71. var inElement string
  72. var r xlsxRow
  73. var tr, tc int
  74. for {
  75. token, _ := decoder.Token()
  76. if token == nil {
  77. break
  78. }
  79. switch startElement := token.(type) {
  80. case xml.StartElement:
  81. inElement = startElement.Name.Local
  82. if inElement == "row" {
  83. r = xlsxRow{}
  84. decoder.DecodeElement(&r, &startElement)
  85. tr = r.R
  86. for _, colCell := range r.C {
  87. col := TitleToNumber(strings.Map(letterOnlyMapF, colCell.R))
  88. if col > tc {
  89. tc = col
  90. }
  91. }
  92. }
  93. default:
  94. }
  95. }
  96. return tr, tc
  97. }
  98. // SetRowHeight provides a function to set the height of a single row. For
  99. // example, set the height of the first row in Sheet1:
  100. //
  101. // xlsx.SetRowHeight("Sheet1", 1, 50)
  102. //
  103. func (f *File) SetRowHeight(sheet string, row int, height float64) {
  104. xlsx := f.workSheetReader(sheet)
  105. cells := 0
  106. rowIdx := row - 1
  107. completeRow(xlsx, row, cells)
  108. xlsx.SheetData.Row[rowIdx].Ht = height
  109. xlsx.SheetData.Row[rowIdx].CustomHeight = true
  110. }
  111. // getRowHeight provides function to get row height in pixels by given sheet
  112. // name and row index.
  113. func (f *File) getRowHeight(sheet string, row int) int {
  114. xlsx := f.workSheetReader(sheet)
  115. for _, v := range xlsx.SheetData.Row {
  116. if v.R == row+1 && v.Ht != 0 {
  117. return int(convertRowHeightToPixels(v.Ht))
  118. }
  119. }
  120. // Optimisation for when the row heights haven't changed.
  121. return int(defaultRowHeightPixels)
  122. }
  123. // GetRowHeight provides function to get row height by given worksheet name
  124. // and row index. For example, get the height of the first row in Sheet1:
  125. //
  126. // xlsx.GetRowHeight("Sheet1", 1)
  127. //
  128. func (f *File) GetRowHeight(sheet string, row int) float64 {
  129. xlsx := f.workSheetReader(sheet)
  130. for _, v := range xlsx.SheetData.Row {
  131. if v.R == row && v.Ht != 0 {
  132. return v.Ht
  133. }
  134. }
  135. // Optimisation for when the row heights haven't changed.
  136. return defaultRowHeightPixels
  137. }
  138. // sharedStringsReader provides function to get the pointer to the structure
  139. // after deserialization of xl/sharedStrings.xml.
  140. func (f *File) sharedStringsReader() *xlsxSST {
  141. if f.SharedStrings == nil {
  142. var sharedStrings xlsxSST
  143. ss := f.readXML("xl/sharedStrings.xml")
  144. if ss == "" {
  145. ss = f.readXML("xl/SharedStrings.xml")
  146. }
  147. xml.Unmarshal([]byte(ss), &sharedStrings)
  148. f.SharedStrings = &sharedStrings
  149. }
  150. return f.SharedStrings
  151. }
  152. // getValueFrom return a value from a column/row cell, this function is inteded
  153. // to be used with for range on rows an argument with the xlsx opened file.
  154. func (xlsx *xlsxC) getValueFrom(f *File, d *xlsxSST) (string, error) {
  155. switch xlsx.T {
  156. case "s":
  157. xlsxSI := 0
  158. xlsxSI, _ = strconv.Atoi(xlsx.V)
  159. if len(d.SI[xlsxSI].R) > 0 {
  160. value := ""
  161. for _, v := range d.SI[xlsxSI].R {
  162. value += v.T
  163. }
  164. return value, nil
  165. }
  166. return f.formattedValue(xlsx.S, d.SI[xlsxSI].T), nil
  167. case "str":
  168. return f.formattedValue(xlsx.S, xlsx.V), nil
  169. case "inlineStr":
  170. return f.formattedValue(xlsx.S, xlsx.IS.T), 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 name and row index. For example, hide row 2 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 name and row index. For example, get visible state of row 2 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 name 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. xlsx.SheetData.Row = append(xlsx.SheetData.Row[:i], xlsx.SheetData.Row[i+1:]...)
  218. f.adjustHelper(sheet, -1, row, -1)
  219. return
  220. }
  221. }
  222. }
  223. // InsertRow provides function to insert a new row before given row index. For
  224. // example, create a new row before row 3 in Sheet1:
  225. //
  226. // xlsx.InsertRow("Sheet1", 2)
  227. //
  228. func (f *File) InsertRow(sheet string, row int) {
  229. if row < 0 {
  230. return
  231. }
  232. row++
  233. f.adjustHelper(sheet, -1, row, 1)
  234. }
  235. // checkRow provides function to check and fill each column element for all rows
  236. // and make that is continuous in a worksheet of XML. For example:
  237. //
  238. // <row r="15" spans="1:22" x14ac:dyDescent="0.2">
  239. // <c r="A15" s="2" />
  240. // <c r="B15" s="2" />
  241. // <c r="F15" s="1" />
  242. // <c r="G15" s="1" />
  243. // </row>
  244. //
  245. // in this case, we should to change it to
  246. //
  247. // <row r="15" spans="1:22" x14ac:dyDescent="0.2">
  248. // <c r="A15" s="2" />
  249. // <c r="B15" s="2" />
  250. // <c r="C15" s="2" />
  251. // <c r="D15" s="2" />
  252. // <c r="E15" s="2" />
  253. // <c r="F15" s="1" />
  254. // <c r="G15" s="1" />
  255. // </row>
  256. //
  257. // Noteice: this method could be very slow for large spreadsheets (more than
  258. // 3000 rows one sheet).
  259. func checkRow(xlsx *xlsxWorksheet) {
  260. buffer := bytes.Buffer{}
  261. for k := range xlsx.SheetData.Row {
  262. lenCol := len(xlsx.SheetData.Row[k].C)
  263. if lenCol > 0 {
  264. endR := string(strings.Map(letterOnlyMapF, xlsx.SheetData.Row[k].C[lenCol-1].R))
  265. endRow, _ := strconv.Atoi(strings.Map(intOnlyMapF, xlsx.SheetData.Row[k].C[lenCol-1].R))
  266. endCol := TitleToNumber(endR) + 1
  267. if lenCol < endCol {
  268. oldRow := xlsx.SheetData.Row[k].C
  269. xlsx.SheetData.Row[k].C = xlsx.SheetData.Row[k].C[:0]
  270. tmp := []xlsxC{}
  271. for i := 0; i < endCol; i++ {
  272. buffer.WriteString(ToAlphaString(i))
  273. buffer.WriteString(strconv.Itoa(endRow))
  274. tmp = append(tmp, xlsxC{
  275. R: buffer.String(),
  276. })
  277. buffer.Reset()
  278. }
  279. xlsx.SheetData.Row[k].C = tmp
  280. for _, y := range oldRow {
  281. colAxis := TitleToNumber(string(strings.Map(letterOnlyMapF, y.R)))
  282. xlsx.SheetData.Row[k].C[colAxis] = y
  283. }
  284. }
  285. }
  286. }
  287. }
  288. // completeRow provides function to check and fill each column element for a
  289. // single row and make that is continuous in a worksheet of XML by given row
  290. // index and axis.
  291. func completeRow(xlsx *xlsxWorksheet, row, cell int) {
  292. currentRows := len(xlsx.SheetData.Row)
  293. if currentRows > 1 {
  294. lastRow := xlsx.SheetData.Row[currentRows-1].R
  295. if lastRow >= row {
  296. row = lastRow
  297. }
  298. }
  299. for i := currentRows; i < row; i++ {
  300. xlsx.SheetData.Row = append(xlsx.SheetData.Row, xlsxRow{
  301. R: i + 1,
  302. })
  303. }
  304. buffer := bytes.Buffer{}
  305. for ii := currentRows; ii < row; ii++ {
  306. start := len(xlsx.SheetData.Row[ii].C)
  307. if start == 0 {
  308. for iii := start; iii < cell; iii++ {
  309. buffer.WriteString(ToAlphaString(iii))
  310. buffer.WriteString(strconv.Itoa(ii + 1))
  311. xlsx.SheetData.Row[ii].C = append(xlsx.SheetData.Row[ii].C, xlsxC{
  312. R: buffer.String(),
  313. })
  314. buffer.Reset()
  315. }
  316. }
  317. }
  318. }
  319. // convertRowHeightToPixels provides function to convert the height of a cell
  320. // from user's units to pixels. If the height hasn't been set by the user we use
  321. // the default value. If the row is hidden it has a value of zero.
  322. func convertRowHeightToPixels(height float64) float64 {
  323. var pixels float64
  324. if height == 0 {
  325. return pixels
  326. }
  327. pixels = math.Ceil(4.0 / 3.0 * height)
  328. return pixels
  329. }