rows.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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.
  99. // For example:
  100. //
  101. // xlsx := excelize.NewFile()
  102. // xlsx.SetRowHeight("Sheet1", 0, 50)
  103. // err := xlsx.Save()
  104. // if err != nil {
  105. // fmt.Println(err)
  106. // }
  107. //
  108. func (f *File) SetRowHeight(sheet string, rowIndex int, height float64) {
  109. xlsx := f.workSheetReader(sheet)
  110. rows := rowIndex + 1
  111. cells := 0
  112. completeRow(xlsx, rows, cells)
  113. xlsx.SheetData.Row[rowIndex].Ht = height
  114. xlsx.SheetData.Row[rowIndex].CustomHeight = true
  115. }
  116. // getRowHeight provides function to get row height in pixels by given sheet
  117. // name and row index.
  118. func (f *File) getRowHeight(sheet string, row int) int {
  119. xlsx := f.workSheetReader(sheet)
  120. for _, v := range xlsx.SheetData.Row {
  121. if v.R == row+1 && v.Ht != 0 {
  122. return int(convertRowHeightToPixels(v.Ht))
  123. }
  124. }
  125. // Optimisation for when the row heights haven't changed.
  126. return int(defaultRowHeightPixels)
  127. }
  128. // GetRowHeight provides function to get row height by given worksheet name and
  129. // row index.
  130. func (f *File) GetRowHeight(sheet string, row int) float64 {
  131. xlsx := f.workSheetReader(sheet)
  132. for _, v := range xlsx.SheetData.Row {
  133. if v.R == row+1 && v.Ht != 0 {
  134. return v.Ht
  135. }
  136. }
  137. // Optimisation for when the row heights haven't changed.
  138. return defaultRowHeightPixels
  139. }
  140. // sharedStringsReader provides function to get the pointer to the structure
  141. // after deserialization of xl/sharedStrings.xml.
  142. func (f *File) sharedStringsReader() *xlsxSST {
  143. if f.SharedStrings == nil {
  144. var sharedStrings xlsxSST
  145. xml.Unmarshal([]byte(f.readXML("xl/sharedStrings.xml")), &sharedStrings)
  146. f.SharedStrings = &sharedStrings
  147. }
  148. return f.SharedStrings
  149. }
  150. // getValueFrom return a value from a column/row cell, this function is inteded
  151. // to be used with for range on rows an argument with the xlsx opened file.
  152. func (xlsx *xlsxC) getValueFrom(f *File, d *xlsxSST) (string, error) {
  153. switch xlsx.T {
  154. case "s":
  155. xlsxSI := 0
  156. xlsxSI, _ = strconv.Atoi(xlsx.V)
  157. if len(d.SI[xlsxSI].R) > 0 {
  158. value := ""
  159. for _, v := range d.SI[xlsxSI].R {
  160. value += v.T
  161. }
  162. return value, nil
  163. }
  164. return f.formattedValue(xlsx.S, d.SI[xlsxSI].T), nil
  165. case "str":
  166. return f.formattedValue(xlsx.S, xlsx.V), nil
  167. default:
  168. return f.formattedValue(xlsx.S, xlsx.V), nil
  169. }
  170. }
  171. // SetRowVisible provides a function to set visible of a single row by given
  172. // worksheet name and row index. For example, hide row 3 in Sheet1:
  173. //
  174. // xlsx.SetRowVisible("Sheet1", 2, false)
  175. //
  176. func (f *File) SetRowVisible(sheet string, rowIndex int, visible bool) {
  177. xlsx := f.workSheetReader(sheet)
  178. rows := rowIndex + 1
  179. cells := 0
  180. completeRow(xlsx, rows, cells)
  181. if visible {
  182. xlsx.SheetData.Row[rowIndex].Hidden = false
  183. return
  184. }
  185. xlsx.SheetData.Row[rowIndex].Hidden = true
  186. }
  187. // GetRowVisible provides a function to get visible of a single row by given
  188. // worksheet name and row index. For example, get visible state of row 3 in
  189. // Sheet1:
  190. //
  191. // xlsx.GetRowVisible("Sheet1", 2)
  192. //
  193. func (f *File) GetRowVisible(sheet string, rowIndex int) bool {
  194. xlsx := f.workSheetReader(sheet)
  195. rows := rowIndex + 1
  196. cells := 0
  197. completeRow(xlsx, rows, cells)
  198. return !xlsx.SheetData.Row[rowIndex].Hidden
  199. }
  200. // RemoveRow provides function to remove single row by given worksheet name and
  201. // row index. For example, remove row 3 in Sheet1:
  202. //
  203. // xlsx.RemoveRow("Sheet1", 2)
  204. //
  205. func (f *File) RemoveRow(sheet string, row int) {
  206. if row < 0 {
  207. return
  208. }
  209. xlsx := f.workSheetReader(sheet)
  210. row++
  211. for i, r := range xlsx.SheetData.Row {
  212. if r.R == row {
  213. xlsx.SheetData.Row = append(xlsx.SheetData.Row[:i], xlsx.SheetData.Row[i+1:]...)
  214. f.adjustHelper(sheet, -1, row, -1)
  215. return
  216. }
  217. }
  218. }
  219. // InsertRow provides function to insert a new row before given row index. For
  220. // example, create a new row before row 3 in Sheet1:
  221. //
  222. // xlsx.InsertRow("Sheet1", 2)
  223. //
  224. func (f *File) InsertRow(sheet string, row int) {
  225. if row < 0 {
  226. return
  227. }
  228. row++
  229. f.adjustHelper(sheet, -1, row, 1)
  230. }
  231. // checkRow provides function to check and fill each column element for all rows
  232. // and make that is continuous in a worksheet of XML. For example:
  233. //
  234. // <row r="15" spans="1:22" x14ac:dyDescent="0.2">
  235. // <c r="A15" s="2" />
  236. // <c r="B15" s="2" />
  237. // <c r="F15" s="1" />
  238. // <c r="G15" s="1" />
  239. // </row>
  240. //
  241. // in this case, we should to change it to
  242. //
  243. // <row r="15" spans="1:22" x14ac:dyDescent="0.2">
  244. // <c r="A15" s="2" />
  245. // <c r="B15" s="2" />
  246. // <c r="C15" s="2" />
  247. // <c r="D15" s="2" />
  248. // <c r="E15" s="2" />
  249. // <c r="F15" s="1" />
  250. // <c r="G15" s="1" />
  251. // </row>
  252. //
  253. // Noteice: this method could be very slow for large spreadsheets (more than
  254. // 3000 rows one sheet).
  255. func checkRow(xlsx *xlsxWorksheet) {
  256. buffer := bytes.Buffer{}
  257. for k := range xlsx.SheetData.Row {
  258. lenCol := len(xlsx.SheetData.Row[k].C)
  259. if lenCol > 0 {
  260. endR := string(strings.Map(letterOnlyMapF, xlsx.SheetData.Row[k].C[lenCol-1].R))
  261. endRow, _ := strconv.Atoi(strings.Map(intOnlyMapF, xlsx.SheetData.Row[k].C[lenCol-1].R))
  262. endCol := TitleToNumber(endR) + 1
  263. if lenCol < endCol {
  264. oldRow := xlsx.SheetData.Row[k].C
  265. xlsx.SheetData.Row[k].C = xlsx.SheetData.Row[k].C[:0]
  266. tmp := []xlsxC{}
  267. for i := 0; i < endCol; i++ {
  268. buffer.WriteString(ToAlphaString(i))
  269. buffer.WriteString(strconv.Itoa(endRow))
  270. tmp = append(tmp, xlsxC{
  271. R: buffer.String(),
  272. })
  273. buffer.Reset()
  274. }
  275. xlsx.SheetData.Row[k].C = tmp
  276. for _, y := range oldRow {
  277. colAxis := TitleToNumber(string(strings.Map(letterOnlyMapF, y.R)))
  278. xlsx.SheetData.Row[k].C[colAxis] = y
  279. }
  280. }
  281. }
  282. }
  283. }
  284. // completeRow provides function to check and fill each column element for a
  285. // single row and make that is continuous in a worksheet of XML by given row
  286. // index and axis.
  287. func completeRow(xlsx *xlsxWorksheet, row, cell int) {
  288. currentRows := len(xlsx.SheetData.Row)
  289. if currentRows > 1 {
  290. lastRow := xlsx.SheetData.Row[currentRows-1].R
  291. if lastRow >= row {
  292. row = lastRow
  293. }
  294. }
  295. for i := currentRows; i < row; i++ {
  296. xlsx.SheetData.Row = append(xlsx.SheetData.Row, xlsxRow{
  297. R: i + 1,
  298. })
  299. }
  300. buffer := bytes.Buffer{}
  301. for ii := currentRows; ii < row; ii++ {
  302. start := len(xlsx.SheetData.Row[ii].C)
  303. if start == 0 {
  304. for iii := start; iii < cell; iii++ {
  305. buffer.WriteString(ToAlphaString(iii))
  306. buffer.WriteString(strconv.Itoa(ii + 1))
  307. xlsx.SheetData.Row[ii].C = append(xlsx.SheetData.Row[ii].C, xlsxC{
  308. R: buffer.String(),
  309. })
  310. buffer.Reset()
  311. }
  312. }
  313. }
  314. }
  315. // convertRowHeightToPixels provides function to convert the height of a cell
  316. // from user's units to pixels. If the height hasn't been set by the user we use
  317. // the default value. If the row is hidden it has a value of zero.
  318. func convertRowHeightToPixels(height float64) float64 {
  319. var pixels float64
  320. if height == 0 {
  321. return pixels
  322. }
  323. pixels = math.Ceil(4.0 / 3.0 * height)
  324. return pixels
  325. }