cell.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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. For example: add
  195. // hyperLink for Sheet1!A3:
  196. //
  197. // xlsx.SetCellHyperLink("Sheet1", "A3", "https://github.com/xuri/excelize")
  198. // // Set underline and font color style for the cell.
  199. // style, _ := xlsx.NewStyle(`{"font":{"color":"#1265BE","underline":"single"}}`)
  200. // xlsx.SetCellStyle("Sheet1", "A3", "A3", style)
  201. //
  202. func (f *File) SetCellHyperLink(sheet, axis, link string) {
  203. xlsx := f.workSheetReader(sheet)
  204. axis = f.mergeCellsParser(xlsx, axis)
  205. rID := f.addSheetRelationships(sheet, SourceRelationshipHyperLink, link, "External")
  206. hyperlink := xlsxHyperlink{
  207. Ref: axis,
  208. RID: "rId" + strconv.Itoa(rID),
  209. }
  210. if xlsx.Hyperlinks != nil {
  211. xlsx.Hyperlinks.Hyperlink = append(xlsx.Hyperlinks.Hyperlink, hyperlink)
  212. } else {
  213. hyperlinks := xlsxHyperlinks{}
  214. hyperlinks.Hyperlink = append(hyperlinks.Hyperlink, hyperlink)
  215. xlsx.Hyperlinks = &hyperlinks
  216. }
  217. }
  218. // MergeCell provides function to merge cells by given coordinate area and sheet
  219. // name. For example create a merged cell of D3:E9 on Sheet1:
  220. //
  221. // xlsx.MergeCell("sheet1", "D3", "E9")
  222. //
  223. // If you create a merged cell that overlaps with another existing merged cell,
  224. // those merged cells that already exist will be removed.
  225. func (f *File) MergeCell(sheet, hcell, vcell string) {
  226. if hcell == vcell {
  227. return
  228. }
  229. hcell = strings.ToUpper(hcell)
  230. vcell = strings.ToUpper(vcell)
  231. // Coordinate conversion, convert C1:B3 to 2,0,1,2.
  232. hcol := string(strings.Map(letterOnlyMapF, hcell))
  233. hrow, _ := strconv.Atoi(strings.Map(intOnlyMapF, hcell))
  234. hyAxis := hrow - 1
  235. hxAxis := TitleToNumber(hcol)
  236. vcol := string(strings.Map(letterOnlyMapF, vcell))
  237. vrow, _ := strconv.Atoi(strings.Map(intOnlyMapF, vcell))
  238. vyAxis := vrow - 1
  239. vxAxis := TitleToNumber(vcol)
  240. if vxAxis < hxAxis {
  241. hcell, vcell = vcell, hcell
  242. vxAxis, hxAxis = hxAxis, vxAxis
  243. }
  244. if vyAxis < hyAxis {
  245. hcell, vcell = vcell, hcell
  246. vyAxis, hyAxis = hyAxis, vyAxis
  247. }
  248. xlsx := f.workSheetReader(sheet)
  249. if xlsx.MergeCells != nil {
  250. mergeCell := xlsxMergeCell{}
  251. // Correct the coordinate area, such correct C1:B3 to B1:C3.
  252. mergeCell.Ref = ToAlphaString(hxAxis) + strconv.Itoa(hyAxis+1) + ":" + ToAlphaString(vxAxis) + strconv.Itoa(vyAxis+1)
  253. // Delete the merged cells of the overlapping area.
  254. for i := 0; i < len(xlsx.MergeCells.Cells); i++ {
  255. if checkCellInArea(hcell, xlsx.MergeCells.Cells[i].Ref) || checkCellInArea(strings.Split(xlsx.MergeCells.Cells[i].Ref, ":")[0], mergeCell.Ref) {
  256. xlsx.MergeCells.Cells = append(xlsx.MergeCells.Cells[:i], xlsx.MergeCells.Cells[i+1:]...)
  257. } else if checkCellInArea(vcell, xlsx.MergeCells.Cells[i].Ref) || checkCellInArea(strings.Split(xlsx.MergeCells.Cells[i].Ref, ":")[1], mergeCell.Ref) {
  258. xlsx.MergeCells.Cells = append(xlsx.MergeCells.Cells[:i], xlsx.MergeCells.Cells[i+1:]...)
  259. }
  260. }
  261. xlsx.MergeCells.Cells = append(xlsx.MergeCells.Cells, &mergeCell)
  262. } else {
  263. mergeCell := xlsxMergeCell{}
  264. // Correct the coordinate area, such correct C1:B3 to B1:C3.
  265. mergeCell.Ref = ToAlphaString(hxAxis) + strconv.Itoa(hyAxis+1) + ":" + ToAlphaString(vxAxis) + strconv.Itoa(vyAxis+1)
  266. mergeCells := xlsxMergeCells{}
  267. mergeCells.Cells = append(mergeCells.Cells, &mergeCell)
  268. xlsx.MergeCells = &mergeCells
  269. }
  270. }
  271. // SetCellInt provides function to set int type value of a cell by given
  272. // worksheet name, cell coordinates and cell value.
  273. func (f *File) SetCellInt(sheet, axis string, value int) {
  274. xlsx := f.workSheetReader(sheet)
  275. axis = f.mergeCellsParser(xlsx, axis)
  276. col := string(strings.Map(letterOnlyMapF, axis))
  277. row, _ := strconv.Atoi(strings.Map(intOnlyMapF, axis))
  278. xAxis := row - 1
  279. yAxis := TitleToNumber(col)
  280. rows := xAxis + 1
  281. cell := yAxis + 1
  282. completeRow(xlsx, rows, cell)
  283. completeCol(xlsx, rows, cell)
  284. xlsx.SheetData.Row[xAxis].C[yAxis].S = f.prepareCellStyle(xlsx, cell, xlsx.SheetData.Row[xAxis].C[yAxis].S)
  285. xlsx.SheetData.Row[xAxis].C[yAxis].T = ""
  286. xlsx.SheetData.Row[xAxis].C[yAxis].V = strconv.Itoa(value)
  287. }
  288. // prepareCellStyle provides function to prepare style index of cell in
  289. // worksheet by given column index and style index.
  290. func (f *File) prepareCellStyle(xlsx *xlsxWorksheet, col, style int) int {
  291. if xlsx.Cols != nil && style == 0 {
  292. for _, v := range xlsx.Cols.Col {
  293. if v.Min <= col && col <= v.Max {
  294. style = v.Style
  295. }
  296. }
  297. }
  298. return style
  299. }
  300. // SetCellStr provides function to set string type value of a cell. Total number
  301. // of characters that a cell can contain 32767 characters.
  302. func (f *File) SetCellStr(sheet, axis, value string) {
  303. xlsx := f.workSheetReader(sheet)
  304. axis = f.mergeCellsParser(xlsx, axis)
  305. if len(value) > 32767 {
  306. value = value[0:32767]
  307. }
  308. col := string(strings.Map(letterOnlyMapF, axis))
  309. row, _ := strconv.Atoi(strings.Map(intOnlyMapF, axis))
  310. xAxis := row - 1
  311. yAxis := TitleToNumber(col)
  312. rows := xAxis + 1
  313. cell := yAxis + 1
  314. completeRow(xlsx, rows, cell)
  315. completeCol(xlsx, rows, cell)
  316. // Leading space(s) character detection.
  317. if len(value) > 0 {
  318. if value[0] == 32 {
  319. xlsx.SheetData.Row[xAxis].C[yAxis].XMLSpace = xml.Attr{
  320. Name: xml.Name{Space: NameSpaceXML, Local: "space"},
  321. Value: "preserve",
  322. }
  323. }
  324. }
  325. xlsx.SheetData.Row[xAxis].C[yAxis].S = f.prepareCellStyle(xlsx, cell, xlsx.SheetData.Row[xAxis].C[yAxis].S)
  326. xlsx.SheetData.Row[xAxis].C[yAxis].T = "str"
  327. xlsx.SheetData.Row[xAxis].C[yAxis].V = value
  328. }
  329. // SetCellDefault provides function to set string type value of a cell as
  330. // default format without escaping the cell.
  331. func (f *File) SetCellDefault(sheet, axis, value string) {
  332. xlsx := f.workSheetReader(sheet)
  333. axis = f.mergeCellsParser(xlsx, axis)
  334. col := string(strings.Map(letterOnlyMapF, axis))
  335. row, _ := strconv.Atoi(strings.Map(intOnlyMapF, axis))
  336. xAxis := row - 1
  337. yAxis := TitleToNumber(col)
  338. rows := xAxis + 1
  339. cell := yAxis + 1
  340. completeRow(xlsx, rows, cell)
  341. completeCol(xlsx, rows, cell)
  342. xlsx.SheetData.Row[xAxis].C[yAxis].S = f.prepareCellStyle(xlsx, cell, xlsx.SheetData.Row[xAxis].C[yAxis].S)
  343. xlsx.SheetData.Row[xAxis].C[yAxis].T = ""
  344. xlsx.SheetData.Row[xAxis].C[yAxis].V = value
  345. }
  346. // checkCellInArea provides function to determine if a given coordinate is
  347. // within an area.
  348. func checkCellInArea(cell, area string) bool {
  349. result := false
  350. cell = strings.ToUpper(cell)
  351. col := string(strings.Map(letterOnlyMapF, cell))
  352. row, _ := strconv.Atoi(strings.Map(intOnlyMapF, cell))
  353. xAxis := row - 1
  354. yAxis := TitleToNumber(col)
  355. ref := strings.Split(area, ":")
  356. hCol := string(strings.Map(letterOnlyMapF, ref[0]))
  357. hRow, _ := strconv.Atoi(strings.Map(intOnlyMapF, ref[0]))
  358. hyAxis := hRow - 1
  359. hxAxis := TitleToNumber(hCol)
  360. vCol := string(strings.Map(letterOnlyMapF, ref[1]))
  361. vRow, _ := strconv.Atoi(strings.Map(intOnlyMapF, ref[1]))
  362. vyAxis := vRow - 1
  363. vxAxis := TitleToNumber(vCol)
  364. if hxAxis <= yAxis && yAxis <= vxAxis && hyAxis <= xAxis && xAxis <= vyAxis {
  365. result = true
  366. }
  367. return result
  368. }