cell.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  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, 64))
  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, err := strconv.Atoi(strings.Map(intOnlyMapF, axis))
  76. if err != nil {
  77. return ""
  78. }
  79. xAxis := row - 1
  80. rows := len(xlsx.SheetData.Row)
  81. if rows > 1 {
  82. lastRow := xlsx.SheetData.Row[rows-1].R
  83. if lastRow >= rows {
  84. rows = lastRow
  85. }
  86. }
  87. if rows < xAxis {
  88. return ""
  89. }
  90. for k := range xlsx.SheetData.Row {
  91. if xlsx.SheetData.Row[k].R == row {
  92. for i := range xlsx.SheetData.Row[k].C {
  93. if axis == xlsx.SheetData.Row[k].C[i].R {
  94. val, _ := xlsx.SheetData.Row[k].C[i].getValueFrom(f, f.sharedStringsReader())
  95. return val
  96. }
  97. }
  98. }
  99. }
  100. return ""
  101. }
  102. // formattedValue provides function to returns a value after formatted. If it is
  103. // possible to apply a format to the cell value, it will do so, if not then an
  104. // error will be returned, along with the raw value of the cell.
  105. func (f *File) formattedValue(s int, v string) string {
  106. if s == 0 {
  107. return v
  108. }
  109. styleSheet := f.stylesReader()
  110. ok := builtInNumFmtFunc[styleSheet.CellXfs.Xf[s].NumFmtID]
  111. if ok != nil {
  112. return ok(styleSheet.CellXfs.Xf[s].NumFmtID, v)
  113. }
  114. return v
  115. }
  116. // GetCellStyle provides function to get cell style index by given worksheet
  117. // name and cell coordinates.
  118. func (f *File) GetCellStyle(sheet, axis string) int {
  119. xlsx := f.workSheetReader(sheet)
  120. axis = f.mergeCellsParser(xlsx, axis)
  121. col := string(strings.Map(letterOnlyMapF, axis))
  122. row, err := strconv.Atoi(strings.Map(intOnlyMapF, axis))
  123. if err != nil {
  124. return 0
  125. }
  126. xAxis := row - 1
  127. yAxis := TitleToNumber(col)
  128. rows := xAxis + 1
  129. cell := yAxis + 1
  130. completeRow(xlsx, rows, cell)
  131. completeCol(xlsx, rows, cell)
  132. return f.prepareCellStyle(xlsx, cell, xlsx.SheetData.Row[xAxis].C[yAxis].S)
  133. }
  134. // GetCellFormula provides function to get formula from cell by given worksheet
  135. // name and axis in XLSX file.
  136. func (f *File) GetCellFormula(sheet, axis string) string {
  137. xlsx := f.workSheetReader(sheet)
  138. axis = f.mergeCellsParser(xlsx, axis)
  139. row, err := strconv.Atoi(strings.Map(intOnlyMapF, axis))
  140. if err != nil {
  141. return ""
  142. }
  143. xAxis := row - 1
  144. rows := len(xlsx.SheetData.Row)
  145. if rows > 1 {
  146. lastRow := xlsx.SheetData.Row[rows-1].R
  147. if lastRow >= rows {
  148. rows = lastRow
  149. }
  150. }
  151. if rows < xAxis {
  152. return ""
  153. }
  154. for k := range xlsx.SheetData.Row {
  155. if xlsx.SheetData.Row[k].R == row {
  156. for i := range xlsx.SheetData.Row[k].C {
  157. if axis == xlsx.SheetData.Row[k].C[i].R {
  158. if xlsx.SheetData.Row[k].C[i].F != nil {
  159. return xlsx.SheetData.Row[k].C[i].F.Content
  160. }
  161. }
  162. }
  163. }
  164. }
  165. return ""
  166. }
  167. // SetCellFormula provides function to set cell formula by given string and
  168. // sheet index.
  169. func (f *File) SetCellFormula(sheet, axis, formula string) {
  170. xlsx := f.workSheetReader(sheet)
  171. axis = f.mergeCellsParser(xlsx, axis)
  172. col := string(strings.Map(letterOnlyMapF, axis))
  173. row, err := strconv.Atoi(strings.Map(intOnlyMapF, axis))
  174. if err != nil {
  175. return
  176. }
  177. xAxis := row - 1
  178. yAxis := TitleToNumber(col)
  179. rows := xAxis + 1
  180. cell := yAxis + 1
  181. completeRow(xlsx, rows, cell)
  182. completeCol(xlsx, rows, cell)
  183. if xlsx.SheetData.Row[xAxis].C[yAxis].F != nil {
  184. xlsx.SheetData.Row[xAxis].C[yAxis].F.Content = formula
  185. } else {
  186. f := xlsxF{
  187. Content: formula,
  188. }
  189. xlsx.SheetData.Row[xAxis].C[yAxis].F = &f
  190. }
  191. }
  192. // SetCellHyperLink provides function to set cell hyperlink by given worksheet
  193. // name and link URL address. LinkType defines two types of hyperlink "External"
  194. // for web site or "Location" for moving to one of cell in this workbook. The
  195. // below is example for external link.
  196. //
  197. // xlsx.SetCellHyperLink("Sheet1", "A3", "https://github.com/xuri/excelize", "External")
  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. // A this is another example for "Location":
  203. //
  204. // xlsx.SetCellHyperLink("Sheet1", "A3", "Sheet1!A40", "Location")
  205. //
  206. func (f *File) SetCellHyperLink(sheet, axis, link, linkType string) {
  207. xlsx := f.workSheetReader(sheet)
  208. axis = f.mergeCellsParser(xlsx, axis)
  209. linkTypes := map[string]xlsxHyperlink{
  210. "External": {},
  211. "Location": {Location: link},
  212. }
  213. hyperlink, ok := linkTypes[linkType]
  214. if !ok || axis == "" {
  215. return
  216. }
  217. hyperlink.Ref = axis
  218. if linkType == "External" {
  219. rID := f.addSheetRelationships(sheet, SourceRelationshipHyperLink, link, linkType)
  220. hyperlink.RID = "rId" + strconv.Itoa(rID)
  221. }
  222. if xlsx.Hyperlinks == nil {
  223. xlsx.Hyperlinks = &xlsxHyperlinks{}
  224. }
  225. xlsx.Hyperlinks.Hyperlink = append(xlsx.Hyperlinks.Hyperlink, hyperlink)
  226. }
  227. // GetCellHyperLink provides function to get cell hyperlink by given worksheet
  228. // name and axis. Boolean type value link will be ture if the cell has a
  229. // hyperlink and the target is the address of the hyperlink. Otherwise, the
  230. // value of link will be false and the value of the target will be a blank
  231. // string. For example get hyperlink of Sheet1!H6:
  232. //
  233. // link, target := xlsx.GetCellHyperLink("Sheet1", "H6")
  234. //
  235. func (f *File) GetCellHyperLink(sheet, axis string) (bool, string) {
  236. var link bool
  237. var target string
  238. xlsx := f.workSheetReader(sheet)
  239. axis = f.mergeCellsParser(xlsx, axis)
  240. if xlsx.Hyperlinks == nil || axis == "" {
  241. return link, target
  242. }
  243. for h := range xlsx.Hyperlinks.Hyperlink {
  244. if xlsx.Hyperlinks.Hyperlink[h].Ref == axis {
  245. link = true
  246. target = xlsx.Hyperlinks.Hyperlink[h].Location
  247. if xlsx.Hyperlinks.Hyperlink[h].RID != "" {
  248. target = f.getSheetRelationshipsTargetByID(sheet, xlsx.Hyperlinks.Hyperlink[h].RID)
  249. }
  250. }
  251. }
  252. return link, target
  253. }
  254. // MergeCell provides function to merge cells by given coordinate area and sheet
  255. // name. For example create a merged cell of D3:E9 on Sheet1:
  256. //
  257. // xlsx.MergeCell("Sheet1", "D3", "E9")
  258. //
  259. // If you create a merged cell that overlaps with another existing merged cell,
  260. // those merged cells that already exist will be removed.
  261. func (f *File) MergeCell(sheet, hcell, vcell string) {
  262. if hcell == vcell {
  263. return
  264. }
  265. hcell = strings.ToUpper(hcell)
  266. vcell = strings.ToUpper(vcell)
  267. // Coordinate conversion, convert C1:B3 to 2,0,1,2.
  268. hcol := string(strings.Map(letterOnlyMapF, hcell))
  269. hrow, _ := strconv.Atoi(strings.Map(intOnlyMapF, hcell))
  270. hyAxis := hrow - 1
  271. hxAxis := TitleToNumber(hcol)
  272. vcol := string(strings.Map(letterOnlyMapF, vcell))
  273. vrow, _ := strconv.Atoi(strings.Map(intOnlyMapF, vcell))
  274. vyAxis := vrow - 1
  275. vxAxis := TitleToNumber(vcol)
  276. if vxAxis < hxAxis {
  277. hcell, vcell = vcell, hcell
  278. vxAxis, hxAxis = hxAxis, vxAxis
  279. }
  280. if vyAxis < hyAxis {
  281. hcell, vcell = vcell, hcell
  282. vyAxis, hyAxis = hyAxis, vyAxis
  283. }
  284. xlsx := f.workSheetReader(sheet)
  285. if xlsx.MergeCells != nil {
  286. mergeCell := xlsxMergeCell{}
  287. // Correct the coordinate area, such correct C1:B3 to B1:C3.
  288. mergeCell.Ref = ToAlphaString(hxAxis) + strconv.Itoa(hyAxis+1) + ":" + ToAlphaString(vxAxis) + strconv.Itoa(vyAxis+1)
  289. // Delete the merged cells of the overlapping area.
  290. for i := 0; i < len(xlsx.MergeCells.Cells); i++ {
  291. if checkCellInArea(hcell, xlsx.MergeCells.Cells[i].Ref) || checkCellInArea(strings.Split(xlsx.MergeCells.Cells[i].Ref, ":")[0], mergeCell.Ref) {
  292. xlsx.MergeCells.Cells = append(xlsx.MergeCells.Cells[:i], xlsx.MergeCells.Cells[i+1:]...)
  293. } else if checkCellInArea(vcell, xlsx.MergeCells.Cells[i].Ref) || checkCellInArea(strings.Split(xlsx.MergeCells.Cells[i].Ref, ":")[1], mergeCell.Ref) {
  294. xlsx.MergeCells.Cells = append(xlsx.MergeCells.Cells[:i], xlsx.MergeCells.Cells[i+1:]...)
  295. }
  296. }
  297. xlsx.MergeCells.Cells = append(xlsx.MergeCells.Cells, &mergeCell)
  298. } else {
  299. mergeCell := xlsxMergeCell{}
  300. // Correct the coordinate area, such correct C1:B3 to B1:C3.
  301. mergeCell.Ref = ToAlphaString(hxAxis) + strconv.Itoa(hyAxis+1) + ":" + ToAlphaString(vxAxis) + strconv.Itoa(vyAxis+1)
  302. mergeCells := xlsxMergeCells{}
  303. mergeCells.Cells = append(mergeCells.Cells, &mergeCell)
  304. xlsx.MergeCells = &mergeCells
  305. }
  306. }
  307. // SetCellInt provides function to set int type value of a cell by given
  308. // worksheet name, cell coordinates and cell value.
  309. func (f *File) SetCellInt(sheet, axis string, value int) {
  310. xlsx := f.workSheetReader(sheet)
  311. axis = f.mergeCellsParser(xlsx, axis)
  312. col := string(strings.Map(letterOnlyMapF, axis))
  313. row, err := strconv.Atoi(strings.Map(intOnlyMapF, axis))
  314. if err != nil {
  315. return
  316. }
  317. xAxis := row - 1
  318. yAxis := TitleToNumber(col)
  319. rows := xAxis + 1
  320. cell := yAxis + 1
  321. completeRow(xlsx, rows, cell)
  322. completeCol(xlsx, rows, cell)
  323. xlsx.SheetData.Row[xAxis].C[yAxis].S = f.prepareCellStyle(xlsx, cell, xlsx.SheetData.Row[xAxis].C[yAxis].S)
  324. xlsx.SheetData.Row[xAxis].C[yAxis].T = ""
  325. xlsx.SheetData.Row[xAxis].C[yAxis].V = strconv.Itoa(value)
  326. }
  327. // prepareCellStyle provides function to prepare style index of cell in
  328. // worksheet by given column index and style index.
  329. func (f *File) prepareCellStyle(xlsx *xlsxWorksheet, col, style int) int {
  330. if xlsx.Cols != nil && style == 0 {
  331. for _, v := range xlsx.Cols.Col {
  332. if v.Min <= col && col <= v.Max {
  333. style = v.Style
  334. }
  335. }
  336. }
  337. return style
  338. }
  339. // SetCellStr provides function to set string type value of a cell. Total number
  340. // of characters that a cell can contain 32767 characters.
  341. func (f *File) SetCellStr(sheet, axis, value string) {
  342. xlsx := f.workSheetReader(sheet)
  343. axis = f.mergeCellsParser(xlsx, axis)
  344. if len(value) > 32767 {
  345. value = value[0:32767]
  346. }
  347. col := string(strings.Map(letterOnlyMapF, axis))
  348. row, err := strconv.Atoi(strings.Map(intOnlyMapF, axis))
  349. if err != nil {
  350. return
  351. }
  352. xAxis := row - 1
  353. yAxis := TitleToNumber(col)
  354. rows := xAxis + 1
  355. cell := yAxis + 1
  356. completeRow(xlsx, rows, cell)
  357. completeCol(xlsx, rows, cell)
  358. // Leading space(s) character detection.
  359. if len(value) > 0 {
  360. if value[0] == 32 {
  361. xlsx.SheetData.Row[xAxis].C[yAxis].XMLSpace = xml.Attr{
  362. Name: xml.Name{Space: NameSpaceXML, Local: "space"},
  363. Value: "preserve",
  364. }
  365. }
  366. }
  367. xlsx.SheetData.Row[xAxis].C[yAxis].S = f.prepareCellStyle(xlsx, cell, xlsx.SheetData.Row[xAxis].C[yAxis].S)
  368. xlsx.SheetData.Row[xAxis].C[yAxis].T = "str"
  369. xlsx.SheetData.Row[xAxis].C[yAxis].V = value
  370. }
  371. // SetCellDefault provides function to set string type value of a cell as
  372. // default format without escaping the cell.
  373. func (f *File) SetCellDefault(sheet, axis, value string) {
  374. xlsx := f.workSheetReader(sheet)
  375. axis = f.mergeCellsParser(xlsx, axis)
  376. col := string(strings.Map(letterOnlyMapF, axis))
  377. row, err := strconv.Atoi(strings.Map(intOnlyMapF, axis))
  378. if err != nil {
  379. return
  380. }
  381. xAxis := row - 1
  382. yAxis := TitleToNumber(col)
  383. rows := xAxis + 1
  384. cell := yAxis + 1
  385. completeRow(xlsx, rows, cell)
  386. completeCol(xlsx, rows, cell)
  387. xlsx.SheetData.Row[xAxis].C[yAxis].S = f.prepareCellStyle(xlsx, cell, xlsx.SheetData.Row[xAxis].C[yAxis].S)
  388. xlsx.SheetData.Row[xAxis].C[yAxis].T = ""
  389. xlsx.SheetData.Row[xAxis].C[yAxis].V = value
  390. }
  391. // checkCellInArea provides function to determine if a given coordinate is
  392. // within an area.
  393. func checkCellInArea(cell, area string) bool {
  394. result := false
  395. cell = strings.ToUpper(cell)
  396. col := string(strings.Map(letterOnlyMapF, cell))
  397. row, _ := strconv.Atoi(strings.Map(intOnlyMapF, cell))
  398. xAxis := row - 1
  399. yAxis := TitleToNumber(col)
  400. ref := strings.Split(area, ":")
  401. hCol := string(strings.Map(letterOnlyMapF, ref[0]))
  402. hRow, _ := strconv.Atoi(strings.Map(intOnlyMapF, ref[0]))
  403. hyAxis := hRow - 1
  404. hxAxis := TitleToNumber(hCol)
  405. vCol := string(strings.Map(letterOnlyMapF, ref[1]))
  406. vRow, _ := strconv.Atoi(strings.Map(intOnlyMapF, ref[1]))
  407. vyAxis := vRow - 1
  408. vxAxis := TitleToNumber(vCol)
  409. if hxAxis <= yAxis && yAxis <= vxAxis && hyAxis <= xAxis && xAxis <= vyAxis {
  410. result = true
  411. }
  412. return result
  413. }