cell.go 13 KB

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