cell.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. package excelize
  2. import (
  3. "encoding/xml"
  4. "fmt"
  5. "strconv"
  6. "strings"
  7. "time"
  8. )
  9. // mergeCellsParser provides function to check merged cells in worksheet by
  10. // given axis.
  11. func (f *File) mergeCellsParser(xlsx *xlsxWorksheet, axis string) string {
  12. axis = strings.ToUpper(axis)
  13. if xlsx.MergeCells != nil {
  14. for i := 0; i < len(xlsx.MergeCells.Cells); i++ {
  15. if checkCellInArea(axis, xlsx.MergeCells.Cells[i].Ref) {
  16. axis = strings.Split(xlsx.MergeCells.Cells[i].Ref, ":")[0]
  17. }
  18. }
  19. }
  20. return axis
  21. }
  22. // SetCellValue provides function to set value of a cell. The following shows
  23. // the supported data types:
  24. //
  25. // int
  26. // int8
  27. // int16
  28. // int32
  29. // int64
  30. // float32
  31. // float64
  32. // string
  33. // []byte
  34. // time.Time
  35. // nil
  36. //
  37. // Note that default date format is m/d/yy h:mm of time.Time type value. You can
  38. // set numbers format by SetCellStyle() method.
  39. func (f *File) SetCellValue(sheet, axis string, value interface{}) {
  40. switch t := value.(type) {
  41. case int:
  42. f.SetCellInt(sheet, axis, value.(int))
  43. case int8:
  44. f.SetCellInt(sheet, axis, int(value.(int8)))
  45. case int16:
  46. f.SetCellInt(sheet, axis, int(value.(int16)))
  47. case int32:
  48. f.SetCellInt(sheet, axis, int(value.(int32)))
  49. case int64:
  50. f.SetCellInt(sheet, axis, int(value.(int64)))
  51. case float32:
  52. f.SetCellDefault(sheet, axis, strconv.FormatFloat(float64(value.(float32)), 'f', -1, 32))
  53. case float64:
  54. f.SetCellDefault(sheet, axis, strconv.FormatFloat(float64(value.(float64)), 'f', -1, 64))
  55. case string:
  56. f.SetCellStr(sheet, axis, t)
  57. case []byte:
  58. f.SetCellStr(sheet, axis, string(t))
  59. case time.Time:
  60. f.SetCellDefault(sheet, axis, strconv.FormatFloat(float64(timeToExcelTime(timeToUTCTime(value.(time.Time)))), 'f', -1, 32))
  61. f.setDefaultTimeStyle(sheet, axis)
  62. case nil:
  63. f.SetCellStr(sheet, axis, "")
  64. default:
  65. f.SetCellStr(sheet, axis, fmt.Sprintf("%v", value))
  66. }
  67. }
  68. // GetCellValue provides function to get formatted value from cell by given
  69. // sheet index and axis in XLSX file. If it is possible to apply a format to the
  70. // cell value, it will do so, if not then an error will be returned, along with
  71. // the raw value of the cell.
  72. func (f *File) GetCellValue(sheet, axis string) string {
  73. xlsx := f.workSheetReader(sheet)
  74. axis = f.mergeCellsParser(xlsx, axis)
  75. row, _ := strconv.Atoi(strings.Map(intOnlyMapF, axis))
  76. xAxis := row - 1
  77. rows := len(xlsx.SheetData.Row)
  78. if rows > 1 {
  79. lastRow := xlsx.SheetData.Row[rows-1].R
  80. if lastRow >= rows {
  81. rows = lastRow
  82. }
  83. }
  84. if rows < xAxis {
  85. return ""
  86. }
  87. for _, v := range xlsx.SheetData.Row {
  88. if v.R != row {
  89. continue
  90. }
  91. for _, r := range v.C {
  92. if axis != r.R {
  93. continue
  94. }
  95. switch r.T {
  96. case "s":
  97. shardStrings := f.sharedStringsReader()
  98. xlsxSI := 0
  99. xlsxSI, _ = strconv.Atoi(r.V)
  100. return f.formattedValue(r.S, shardStrings.SI[xlsxSI].T)
  101. case "str":
  102. return f.formattedValue(r.S, r.V)
  103. default:
  104. return f.formattedValue(r.S, r.V)
  105. }
  106. }
  107. }
  108. return ""
  109. }
  110. // formattedValue provides function to returns a value after formatted. If it is
  111. // possible to apply a format to the cell value, it will do so, if not then an
  112. // error will be returned, along with the raw value of the cell.
  113. func (f *File) formattedValue(s int, v string) string {
  114. if s == 0 {
  115. return v
  116. }
  117. styleSheet := f.stylesReader()
  118. ok := builtInNumFmtFunc[styleSheet.CellXfs.Xf[s].NumFmtID]
  119. if ok != nil {
  120. return ok(styleSheet.CellXfs.Xf[s].NumFmtID, v)
  121. }
  122. return v
  123. }
  124. // GetCellStyle provides function to get cell style index by given worksheet
  125. // name and cell coordinates.
  126. func (f *File) GetCellStyle(sheet, axis string) int {
  127. xlsx := f.workSheetReader(sheet)
  128. axis = f.mergeCellsParser(xlsx, axis)
  129. col := string(strings.Map(letterOnlyMapF, axis))
  130. row, _ := strconv.Atoi(strings.Map(intOnlyMapF, axis))
  131. xAxis := row - 1
  132. yAxis := TitleToNumber(col)
  133. rows := xAxis + 1
  134. cell := yAxis + 1
  135. completeRow(xlsx, rows, cell)
  136. completeCol(xlsx, rows, cell)
  137. return f.prepareCellStyle(xlsx, cell, xlsx.SheetData.Row[xAxis].C[yAxis].S)
  138. }
  139. // GetCellFormula provides function to get formula from cell by given sheet
  140. // index and axis in XLSX file.
  141. func (f *File) GetCellFormula(sheet, axis string) string {
  142. xlsx := f.workSheetReader(sheet)
  143. axis = f.mergeCellsParser(xlsx, axis)
  144. row, _ := strconv.Atoi(strings.Map(intOnlyMapF, axis))
  145. xAxis := row - 1
  146. rows := len(xlsx.SheetData.Row)
  147. if rows > 1 {
  148. lastRow := xlsx.SheetData.Row[rows-1].R
  149. if lastRow >= rows {
  150. rows = lastRow
  151. }
  152. }
  153. if rows < xAxis {
  154. return ""
  155. }
  156. for _, v := range xlsx.SheetData.Row {
  157. if v.R != row {
  158. continue
  159. }
  160. for _, f := range v.C {
  161. if axis != f.R {
  162. continue
  163. }
  164. if f.F != nil {
  165. return f.F.Content
  166. }
  167. }
  168. }
  169. return ""
  170. }
  171. // SetCellFormula provides function to set cell formula by given string and
  172. // sheet index.
  173. func (f *File) SetCellFormula(sheet, axis, formula string) {
  174. xlsx := f.workSheetReader(sheet)
  175. axis = f.mergeCellsParser(xlsx, axis)
  176. col := string(strings.Map(letterOnlyMapF, axis))
  177. row, _ := strconv.Atoi(strings.Map(intOnlyMapF, axis))
  178. xAxis := row - 1
  179. yAxis := TitleToNumber(col)
  180. rows := xAxis + 1
  181. cell := yAxis + 1
  182. completeRow(xlsx, rows, cell)
  183. completeCol(xlsx, rows, cell)
  184. if xlsx.SheetData.Row[xAxis].C[yAxis].F != nil {
  185. xlsx.SheetData.Row[xAxis].C[yAxis].F.Content = formula
  186. } else {
  187. f := xlsxF{
  188. Content: formula,
  189. }
  190. xlsx.SheetData.Row[xAxis].C[yAxis].F = &f
  191. }
  192. }
  193. // SetCellHyperLink provides function to set cell hyperlink by given sheet index
  194. // and link URL address. Only support external link currently.
  195. func (f *File) SetCellHyperLink(sheet, axis, link string) {
  196. xlsx := f.workSheetReader(sheet)
  197. axis = f.mergeCellsParser(xlsx, axis)
  198. rID := f.addSheetRelationships(sheet, SourceRelationshipHyperLink, link, "External")
  199. hyperlink := xlsxHyperlink{
  200. Ref: axis,
  201. RID: "rId" + strconv.Itoa(rID),
  202. }
  203. if xlsx.Hyperlinks != nil {
  204. xlsx.Hyperlinks.Hyperlink = append(xlsx.Hyperlinks.Hyperlink, hyperlink)
  205. } else {
  206. hyperlinks := xlsxHyperlinks{}
  207. hyperlinks.Hyperlink = append(hyperlinks.Hyperlink, hyperlink)
  208. xlsx.Hyperlinks = &hyperlinks
  209. }
  210. }
  211. // MergeCell provides function to merge cells by given coordinate area and sheet
  212. // name. For example create a merged cell of D3:E9 on Sheet1:
  213. //
  214. // xlsx.MergeCell("sheet1", "D3", "E9")
  215. //
  216. // If you create a merged cell that overlaps with another existing merged cell,
  217. // those merged cells that already exist will be removed.
  218. func (f *File) MergeCell(sheet, hcell, vcell string) {
  219. if hcell == vcell {
  220. return
  221. }
  222. hcell = strings.ToUpper(hcell)
  223. vcell = strings.ToUpper(vcell)
  224. // Coordinate conversion, convert C1:B3 to 2,0,1,2.
  225. hcol := string(strings.Map(letterOnlyMapF, hcell))
  226. hrow, _ := strconv.Atoi(strings.Map(intOnlyMapF, hcell))
  227. hyAxis := hrow - 1
  228. hxAxis := TitleToNumber(hcol)
  229. vcol := string(strings.Map(letterOnlyMapF, vcell))
  230. vrow, _ := strconv.Atoi(strings.Map(intOnlyMapF, vcell))
  231. vyAxis := vrow - 1
  232. vxAxis := TitleToNumber(vcol)
  233. if vxAxis < hxAxis {
  234. hcell, vcell = vcell, hcell
  235. vxAxis, hxAxis = hxAxis, vxAxis
  236. }
  237. if vyAxis < hyAxis {
  238. hcell, vcell = vcell, hcell
  239. vyAxis, hyAxis = hyAxis, vyAxis
  240. }
  241. xlsx := f.workSheetReader(sheet)
  242. if xlsx.MergeCells != nil {
  243. mergeCell := xlsxMergeCell{}
  244. // Correct the coordinate area, such correct C1:B3 to B1:C3.
  245. mergeCell.Ref = ToAlphaString(hxAxis) + strconv.Itoa(hyAxis+1) + ":" + ToAlphaString(vxAxis) + strconv.Itoa(vyAxis+1)
  246. // Delete the merged cells of the overlapping area.
  247. for i := 0; i < len(xlsx.MergeCells.Cells); i++ {
  248. if checkCellInArea(hcell, xlsx.MergeCells.Cells[i].Ref) || checkCellInArea(strings.Split(xlsx.MergeCells.Cells[i].Ref, ":")[0], mergeCell.Ref) {
  249. xlsx.MergeCells.Cells = append(xlsx.MergeCells.Cells[:i], xlsx.MergeCells.Cells[i+1:]...)
  250. } else if checkCellInArea(vcell, xlsx.MergeCells.Cells[i].Ref) || checkCellInArea(strings.Split(xlsx.MergeCells.Cells[i].Ref, ":")[1], mergeCell.Ref) {
  251. xlsx.MergeCells.Cells = append(xlsx.MergeCells.Cells[:i], xlsx.MergeCells.Cells[i+1:]...)
  252. }
  253. }
  254. xlsx.MergeCells.Cells = append(xlsx.MergeCells.Cells, &mergeCell)
  255. } else {
  256. mergeCell := xlsxMergeCell{}
  257. // Correct the coordinate area, such correct C1:B3 to B1:C3.
  258. mergeCell.Ref = ToAlphaString(hxAxis) + strconv.Itoa(hyAxis+1) + ":" + ToAlphaString(vxAxis) + strconv.Itoa(vyAxis+1)
  259. mergeCells := xlsxMergeCells{}
  260. mergeCells.Cells = append(mergeCells.Cells, &mergeCell)
  261. xlsx.MergeCells = &mergeCells
  262. }
  263. }
  264. // SetCellInt provides function to set int type value of a cell by given
  265. // worksheet name, cell coordinates and cell value.
  266. func (f *File) SetCellInt(sheet, axis string, value int) {
  267. xlsx := f.workSheetReader(sheet)
  268. axis = f.mergeCellsParser(xlsx, axis)
  269. col := string(strings.Map(letterOnlyMapF, axis))
  270. row, _ := strconv.Atoi(strings.Map(intOnlyMapF, axis))
  271. xAxis := row - 1
  272. yAxis := TitleToNumber(col)
  273. rows := xAxis + 1
  274. cell := yAxis + 1
  275. completeRow(xlsx, rows, cell)
  276. completeCol(xlsx, rows, cell)
  277. xlsx.SheetData.Row[xAxis].C[yAxis].S = f.prepareCellStyle(xlsx, cell, xlsx.SheetData.Row[xAxis].C[yAxis].S)
  278. xlsx.SheetData.Row[xAxis].C[yAxis].T = ""
  279. xlsx.SheetData.Row[xAxis].C[yAxis].V = strconv.Itoa(value)
  280. }
  281. // prepareCellStyle provides function to prepare style index of cell in
  282. // worksheet by given column index and style index.
  283. func (f *File) prepareCellStyle(xlsx *xlsxWorksheet, col, style int) int {
  284. if xlsx.Cols != nil && style == 0 {
  285. for _, v := range xlsx.Cols.Col {
  286. if v.Min <= col && col <= v.Max {
  287. style = v.Style
  288. }
  289. }
  290. }
  291. return style
  292. }
  293. // SetCellStr provides function to set string type value of a cell. Total number
  294. // of characters that a cell can contain 32767 characters.
  295. func (f *File) SetCellStr(sheet, axis, value string) {
  296. xlsx := f.workSheetReader(sheet)
  297. axis = f.mergeCellsParser(xlsx, axis)
  298. if len(value) > 32767 {
  299. value = value[0:32767]
  300. }
  301. col := string(strings.Map(letterOnlyMapF, axis))
  302. row, _ := strconv.Atoi(strings.Map(intOnlyMapF, axis))
  303. xAxis := row - 1
  304. yAxis := TitleToNumber(col)
  305. rows := xAxis + 1
  306. cell := yAxis + 1
  307. completeRow(xlsx, rows, cell)
  308. completeCol(xlsx, rows, cell)
  309. // Leading space(s) character detection.
  310. if len(value) > 0 {
  311. if value[0] == 32 {
  312. xlsx.SheetData.Row[xAxis].C[yAxis].XMLSpace = xml.Attr{
  313. Name: xml.Name{Space: NameSpaceXML, Local: "space"},
  314. Value: "preserve",
  315. }
  316. }
  317. }
  318. xlsx.SheetData.Row[xAxis].C[yAxis].S = f.prepareCellStyle(xlsx, cell, xlsx.SheetData.Row[xAxis].C[yAxis].S)
  319. xlsx.SheetData.Row[xAxis].C[yAxis].T = "str"
  320. xlsx.SheetData.Row[xAxis].C[yAxis].V = value
  321. }
  322. // SetCellDefault provides function to set string type value of a cell as
  323. // default format without escaping the cell.
  324. func (f *File) SetCellDefault(sheet, axis, value string) {
  325. xlsx := f.workSheetReader(sheet)
  326. axis = f.mergeCellsParser(xlsx, axis)
  327. col := string(strings.Map(letterOnlyMapF, axis))
  328. row, _ := strconv.Atoi(strings.Map(intOnlyMapF, axis))
  329. xAxis := row - 1
  330. yAxis := TitleToNumber(col)
  331. rows := xAxis + 1
  332. cell := yAxis + 1
  333. completeRow(xlsx, rows, cell)
  334. completeCol(xlsx, rows, cell)
  335. xlsx.SheetData.Row[xAxis].C[yAxis].S = f.prepareCellStyle(xlsx, cell, xlsx.SheetData.Row[xAxis].C[yAxis].S)
  336. xlsx.SheetData.Row[xAxis].C[yAxis].T = ""
  337. xlsx.SheetData.Row[xAxis].C[yAxis].V = value
  338. }
  339. // checkCellInArea provides function to determine if a given coordinate is
  340. // within an area.
  341. func checkCellInArea(cell, area string) bool {
  342. result := false
  343. cell = strings.ToUpper(cell)
  344. col := string(strings.Map(letterOnlyMapF, cell))
  345. row, _ := strconv.Atoi(strings.Map(intOnlyMapF, cell))
  346. xAxis := row - 1
  347. yAxis := TitleToNumber(col)
  348. ref := strings.Split(area, ":")
  349. hCol := string(strings.Map(letterOnlyMapF, ref[0]))
  350. hRow, _ := strconv.Atoi(strings.Map(intOnlyMapF, ref[0]))
  351. hyAxis := hRow - 1
  352. hxAxis := TitleToNumber(hCol)
  353. vCol := string(strings.Map(letterOnlyMapF, ref[1]))
  354. vRow, _ := strconv.Atoi(strings.Map(intOnlyMapF, ref[1]))
  355. vyAxis := vRow - 1
  356. vxAxis := TitleToNumber(vCol)
  357. if hxAxis <= yAxis && yAxis <= vxAxis && hyAxis <= xAxis && xAxis <= vyAxis {
  358. result = true
  359. }
  360. return result
  361. }