rows.go 9.1 KB

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