cell.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  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. // uint
  31. // uint8
  32. // uint16
  33. // uint32
  34. // uint64
  35. // float32
  36. // float64
  37. // string
  38. // []byte
  39. // time.Duration
  40. // time.Time
  41. // bool
  42. // nil
  43. //
  44. // Note that default date format is m/d/yy h:mm of time.Time type value. You can
  45. // set numbers format by SetCellStyle() method.
  46. func (f *File) SetCellValue(sheet, axis string, value interface{}) {
  47. switch t := value.(type) {
  48. case float32:
  49. f.SetCellDefault(sheet, axis, strconv.FormatFloat(float64(value.(float32)), 'f', -1, 32))
  50. case float64:
  51. f.SetCellDefault(sheet, axis, strconv.FormatFloat(float64(value.(float64)), 'f', -1, 64))
  52. case string:
  53. f.SetCellStr(sheet, axis, t)
  54. case []byte:
  55. f.SetCellStr(sheet, axis, string(t))
  56. case time.Duration:
  57. f.SetCellDefault(sheet, axis, strconv.FormatFloat(float64(value.(time.Duration).Seconds()/86400), 'f', -1, 32))
  58. f.setDefaultTimeStyle(sheet, axis, 21)
  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, 22)
  62. case nil:
  63. f.SetCellStr(sheet, axis, "")
  64. case bool:
  65. f.SetCellBool(sheet, axis, bool(value.(bool)))
  66. default:
  67. f.setCellIntValue(sheet, axis, value)
  68. }
  69. }
  70. // setCellIntValue provides function to set int value of a cell.
  71. func (f *File) setCellIntValue(sheet, axis string, value interface{}) {
  72. switch value.(type) {
  73. case int:
  74. f.SetCellInt(sheet, axis, value.(int))
  75. case int8:
  76. f.SetCellInt(sheet, axis, int(value.(int8)))
  77. case int16:
  78. f.SetCellInt(sheet, axis, int(value.(int16)))
  79. case int32:
  80. f.SetCellInt(sheet, axis, int(value.(int32)))
  81. case int64:
  82. f.SetCellInt(sheet, axis, int(value.(int64)))
  83. case uint:
  84. f.SetCellInt(sheet, axis, int(value.(uint)))
  85. case uint8:
  86. f.SetCellInt(sheet, axis, int(value.(uint8)))
  87. case uint16:
  88. f.SetCellInt(sheet, axis, int(value.(uint16)))
  89. case uint32:
  90. f.SetCellInt(sheet, axis, int(value.(uint32)))
  91. case uint64:
  92. f.SetCellInt(sheet, axis, int(value.(uint64)))
  93. default:
  94. f.SetCellStr(sheet, axis, fmt.Sprintf("%v", value))
  95. }
  96. }
  97. // SetCellBool provides function to set bool type value of a cell by given
  98. // worksheet name, cell coordinates and cell value.
  99. func (f *File) SetCellBool(sheet, axis string, value bool) {
  100. xlsx := f.workSheetReader(sheet)
  101. axis = f.mergeCellsParser(xlsx, axis)
  102. col := string(strings.Map(letterOnlyMapF, axis))
  103. row, err := strconv.Atoi(strings.Map(intOnlyMapF, axis))
  104. if err != nil {
  105. return
  106. }
  107. xAxis := row - 1
  108. yAxis := TitleToNumber(col)
  109. rows := xAxis + 1
  110. cell := yAxis + 1
  111. completeRow(xlsx, rows, cell)
  112. completeCol(xlsx, rows, cell)
  113. xlsx.SheetData.Row[xAxis].C[yAxis].S = f.prepareCellStyle(xlsx, cell, xlsx.SheetData.Row[xAxis].C[yAxis].S)
  114. xlsx.SheetData.Row[xAxis].C[yAxis].T = "b"
  115. if value {
  116. xlsx.SheetData.Row[xAxis].C[yAxis].V = "1"
  117. } else {
  118. xlsx.SheetData.Row[xAxis].C[yAxis].V = "0"
  119. }
  120. }
  121. // GetCellValue provides function to get formatted value from cell by given
  122. // worksheet name and axis in XLSX file. If it is possible to apply a format to
  123. // the cell value, it will do so, if not then an error will be returned, along
  124. // with the raw value of the cell.
  125. func (f *File) GetCellValue(sheet, axis string) string {
  126. xlsx := f.workSheetReader(sheet)
  127. axis = f.mergeCellsParser(xlsx, axis)
  128. row, err := strconv.Atoi(strings.Map(intOnlyMapF, axis))
  129. if err != nil {
  130. return ""
  131. }
  132. xAxis := row - 1
  133. rows := len(xlsx.SheetData.Row)
  134. if rows > 1 {
  135. lastRow := xlsx.SheetData.Row[rows-1].R
  136. if lastRow >= rows {
  137. rows = lastRow
  138. }
  139. }
  140. if rows < xAxis {
  141. return ""
  142. }
  143. for k := range xlsx.SheetData.Row {
  144. if xlsx.SheetData.Row[k].R == row {
  145. for i := range xlsx.SheetData.Row[k].C {
  146. if axis == xlsx.SheetData.Row[k].C[i].R {
  147. val, _ := xlsx.SheetData.Row[k].C[i].getValueFrom(f, f.sharedStringsReader())
  148. return val
  149. }
  150. }
  151. }
  152. }
  153. return ""
  154. }
  155. // formattedValue provides function to returns a value after formatted. If it is
  156. // possible to apply a format to the cell value, it will do so, if not then an
  157. // error will be returned, along with the raw value of the cell.
  158. func (f *File) formattedValue(s int, v string) string {
  159. if s == 0 {
  160. return v
  161. }
  162. styleSheet := f.stylesReader()
  163. ok := builtInNumFmtFunc[styleSheet.CellXfs.Xf[s].NumFmtID]
  164. if ok != nil {
  165. return ok(styleSheet.CellXfs.Xf[s].NumFmtID, v)
  166. }
  167. return v
  168. }
  169. // GetCellStyle provides function to get cell style index by given worksheet
  170. // name and cell coordinates.
  171. func (f *File) GetCellStyle(sheet, axis string) int {
  172. xlsx := f.workSheetReader(sheet)
  173. axis = f.mergeCellsParser(xlsx, axis)
  174. col := string(strings.Map(letterOnlyMapF, axis))
  175. row, err := strconv.Atoi(strings.Map(intOnlyMapF, axis))
  176. if err != nil {
  177. return 0
  178. }
  179. xAxis := row - 1
  180. yAxis := TitleToNumber(col)
  181. rows := xAxis + 1
  182. cell := yAxis + 1
  183. completeRow(xlsx, rows, cell)
  184. completeCol(xlsx, rows, cell)
  185. return f.prepareCellStyle(xlsx, cell, xlsx.SheetData.Row[xAxis].C[yAxis].S)
  186. }
  187. // GetCellFormula provides function to get formula from cell by given worksheet
  188. // name and axis in XLSX file.
  189. func (f *File) GetCellFormula(sheet, axis string) string {
  190. xlsx := f.workSheetReader(sheet)
  191. axis = f.mergeCellsParser(xlsx, axis)
  192. row, err := strconv.Atoi(strings.Map(intOnlyMapF, axis))
  193. if err != nil {
  194. return ""
  195. }
  196. xAxis := row - 1
  197. rows := len(xlsx.SheetData.Row)
  198. if rows > 1 {
  199. lastRow := xlsx.SheetData.Row[rows-1].R
  200. if lastRow >= rows {
  201. rows = lastRow
  202. }
  203. }
  204. if rows < xAxis {
  205. return ""
  206. }
  207. for k := range xlsx.SheetData.Row {
  208. if xlsx.SheetData.Row[k].R == row {
  209. for i := range xlsx.SheetData.Row[k].C {
  210. if axis == xlsx.SheetData.Row[k].C[i].R {
  211. if xlsx.SheetData.Row[k].C[i].F != nil {
  212. return xlsx.SheetData.Row[k].C[i].F.Content
  213. }
  214. }
  215. }
  216. }
  217. }
  218. return ""
  219. }
  220. // SetCellFormula provides function to set cell formula by given string and
  221. // worksheet name.
  222. func (f *File) SetCellFormula(sheet, axis, formula string) {
  223. xlsx := f.workSheetReader(sheet)
  224. axis = f.mergeCellsParser(xlsx, axis)
  225. col := string(strings.Map(letterOnlyMapF, axis))
  226. row, err := strconv.Atoi(strings.Map(intOnlyMapF, axis))
  227. if err != nil {
  228. return
  229. }
  230. xAxis := row - 1
  231. yAxis := TitleToNumber(col)
  232. rows := xAxis + 1
  233. cell := yAxis + 1
  234. completeRow(xlsx, rows, cell)
  235. completeCol(xlsx, rows, cell)
  236. if xlsx.SheetData.Row[xAxis].C[yAxis].F != nil {
  237. xlsx.SheetData.Row[xAxis].C[yAxis].F.Content = formula
  238. } else {
  239. f := xlsxF{
  240. Content: formula,
  241. }
  242. xlsx.SheetData.Row[xAxis].C[yAxis].F = &f
  243. }
  244. }
  245. // SetCellHyperLink provides function to set cell hyperlink by given worksheet
  246. // name and link URL address. LinkType defines two types of hyperlink "External"
  247. // for web site or "Location" for moving to one of cell in this workbook. The
  248. // below is example for external link.
  249. //
  250. // xlsx.SetCellHyperLink("Sheet1", "A3", "https://github.com/360EntSecGroup-Skylar/excelize", "External")
  251. // // Set underline and font color style for the cell.
  252. // style, _ := xlsx.NewStyle(`{"font":{"color":"#1265BE","underline":"single"}}`)
  253. // xlsx.SetCellStyle("Sheet1", "A3", "A3", style)
  254. //
  255. // A this is another example for "Location":
  256. //
  257. // xlsx.SetCellHyperLink("Sheet1", "A3", "Sheet1!A40", "Location")
  258. //
  259. func (f *File) SetCellHyperLink(sheet, axis, link, linkType string) {
  260. xlsx := f.workSheetReader(sheet)
  261. axis = f.mergeCellsParser(xlsx, axis)
  262. linkTypes := map[string]xlsxHyperlink{
  263. "External": {},
  264. "Location": {Location: link},
  265. }
  266. hyperlink, ok := linkTypes[linkType]
  267. if !ok || axis == "" {
  268. return
  269. }
  270. hyperlink.Ref = axis
  271. if linkType == "External" {
  272. rID := f.addSheetRelationships(sheet, SourceRelationshipHyperLink, link, linkType)
  273. hyperlink.RID = "rId" + strconv.Itoa(rID)
  274. }
  275. if xlsx.Hyperlinks == nil {
  276. xlsx.Hyperlinks = &xlsxHyperlinks{}
  277. }
  278. xlsx.Hyperlinks.Hyperlink = append(xlsx.Hyperlinks.Hyperlink, hyperlink)
  279. }
  280. // GetCellHyperLink provides function to get cell hyperlink by given worksheet
  281. // name and axis. Boolean type value link will be ture if the cell has a
  282. // hyperlink and the target is the address of the hyperlink. Otherwise, the
  283. // value of link will be false and the value of the target will be a blank
  284. // string. For example get hyperlink of Sheet1!H6:
  285. //
  286. // link, target := xlsx.GetCellHyperLink("Sheet1", "H6")
  287. //
  288. func (f *File) GetCellHyperLink(sheet, axis string) (bool, string) {
  289. var link bool
  290. var target string
  291. xlsx := f.workSheetReader(sheet)
  292. axis = f.mergeCellsParser(xlsx, axis)
  293. if xlsx.Hyperlinks == nil || axis == "" {
  294. return link, target
  295. }
  296. for h := range xlsx.Hyperlinks.Hyperlink {
  297. if xlsx.Hyperlinks.Hyperlink[h].Ref == axis {
  298. link = true
  299. target = xlsx.Hyperlinks.Hyperlink[h].Location
  300. if xlsx.Hyperlinks.Hyperlink[h].RID != "" {
  301. target = f.getSheetRelationshipsTargetByID(sheet, xlsx.Hyperlinks.Hyperlink[h].RID)
  302. }
  303. }
  304. }
  305. return link, target
  306. }
  307. // MergeCell provides function to merge cells by given coordinate area and sheet
  308. // name. For example create a merged cell of D3:E9 on Sheet1:
  309. //
  310. // xlsx.MergeCell("Sheet1", "D3", "E9")
  311. //
  312. // If you create a merged cell that overlaps with another existing merged cell,
  313. // those merged cells that already exist will be removed.
  314. func (f *File) MergeCell(sheet, hcell, vcell string) {
  315. if hcell == vcell {
  316. return
  317. }
  318. hcell = strings.ToUpper(hcell)
  319. vcell = strings.ToUpper(vcell)
  320. // Coordinate conversion, convert C1:B3 to 2,0,1,2.
  321. hcol := string(strings.Map(letterOnlyMapF, hcell))
  322. hrow, _ := strconv.Atoi(strings.Map(intOnlyMapF, hcell))
  323. hyAxis := hrow - 1
  324. hxAxis := TitleToNumber(hcol)
  325. vcol := string(strings.Map(letterOnlyMapF, vcell))
  326. vrow, _ := strconv.Atoi(strings.Map(intOnlyMapF, vcell))
  327. vyAxis := vrow - 1
  328. vxAxis := TitleToNumber(vcol)
  329. if vxAxis < hxAxis {
  330. hcell, vcell = vcell, hcell
  331. vxAxis, hxAxis = hxAxis, vxAxis
  332. }
  333. if vyAxis < hyAxis {
  334. hcell, vcell = vcell, hcell
  335. vyAxis, hyAxis = hyAxis, vyAxis
  336. }
  337. xlsx := f.workSheetReader(sheet)
  338. if xlsx.MergeCells != nil {
  339. mergeCell := xlsxMergeCell{}
  340. // Correct the coordinate area, such correct C1:B3 to B1:C3.
  341. mergeCell.Ref = ToAlphaString(hxAxis) + strconv.Itoa(hyAxis+1) + ":" + ToAlphaString(vxAxis) + strconv.Itoa(vyAxis+1)
  342. // Delete the merged cells of the overlapping area.
  343. for i := 0; i < len(xlsx.MergeCells.Cells); i++ {
  344. if checkCellInArea(hcell, xlsx.MergeCells.Cells[i].Ref) || checkCellInArea(strings.Split(xlsx.MergeCells.Cells[i].Ref, ":")[0], mergeCell.Ref) {
  345. xlsx.MergeCells.Cells = append(xlsx.MergeCells.Cells[:i], xlsx.MergeCells.Cells[i+1:]...)
  346. } else if checkCellInArea(vcell, xlsx.MergeCells.Cells[i].Ref) || checkCellInArea(strings.Split(xlsx.MergeCells.Cells[i].Ref, ":")[1], mergeCell.Ref) {
  347. xlsx.MergeCells.Cells = append(xlsx.MergeCells.Cells[:i], xlsx.MergeCells.Cells[i+1:]...)
  348. }
  349. }
  350. xlsx.MergeCells.Cells = append(xlsx.MergeCells.Cells, &mergeCell)
  351. } else {
  352. mergeCell := xlsxMergeCell{}
  353. // Correct the coordinate area, such correct C1:B3 to B1:C3.
  354. mergeCell.Ref = ToAlphaString(hxAxis) + strconv.Itoa(hyAxis+1) + ":" + ToAlphaString(vxAxis) + strconv.Itoa(vyAxis+1)
  355. mergeCells := xlsxMergeCells{}
  356. mergeCells.Cells = append(mergeCells.Cells, &mergeCell)
  357. xlsx.MergeCells = &mergeCells
  358. }
  359. }
  360. // SetCellInt provides function to set int type value of a cell by given
  361. // worksheet name, cell coordinates and cell value.
  362. func (f *File) SetCellInt(sheet, axis string, value int) {
  363. xlsx := f.workSheetReader(sheet)
  364. axis = f.mergeCellsParser(xlsx, axis)
  365. col := string(strings.Map(letterOnlyMapF, axis))
  366. row, err := strconv.Atoi(strings.Map(intOnlyMapF, axis))
  367. if err != nil {
  368. return
  369. }
  370. xAxis := row - 1
  371. yAxis := TitleToNumber(col)
  372. rows := xAxis + 1
  373. cell := yAxis + 1
  374. completeRow(xlsx, rows, cell)
  375. completeCol(xlsx, rows, cell)
  376. xlsx.SheetData.Row[xAxis].C[yAxis].S = f.prepareCellStyle(xlsx, cell, xlsx.SheetData.Row[xAxis].C[yAxis].S)
  377. xlsx.SheetData.Row[xAxis].C[yAxis].T = ""
  378. xlsx.SheetData.Row[xAxis].C[yAxis].V = strconv.Itoa(value)
  379. }
  380. // prepareCellStyle provides function to prepare style index of cell in
  381. // worksheet by given column index and style index.
  382. func (f *File) prepareCellStyle(xlsx *xlsxWorksheet, col, style int) int {
  383. if xlsx.Cols != nil && style == 0 {
  384. for _, v := range xlsx.Cols.Col {
  385. if v.Min <= col && col <= v.Max {
  386. style = v.Style
  387. }
  388. }
  389. }
  390. return style
  391. }
  392. // SetCellStr provides function to set string type value of a cell. Total number
  393. // of characters that a cell can contain 32767 characters.
  394. func (f *File) SetCellStr(sheet, axis, value string) {
  395. xlsx := f.workSheetReader(sheet)
  396. axis = f.mergeCellsParser(xlsx, axis)
  397. if len(value) > 32767 {
  398. value = value[0:32767]
  399. }
  400. col := string(strings.Map(letterOnlyMapF, axis))
  401. row, err := strconv.Atoi(strings.Map(intOnlyMapF, axis))
  402. if err != nil {
  403. return
  404. }
  405. xAxis := row - 1
  406. yAxis := TitleToNumber(col)
  407. rows := xAxis + 1
  408. cell := yAxis + 1
  409. completeRow(xlsx, rows, cell)
  410. completeCol(xlsx, rows, cell)
  411. // Leading space(s) character detection.
  412. if len(value) > 0 {
  413. if value[0] == 32 {
  414. xlsx.SheetData.Row[xAxis].C[yAxis].XMLSpace = xml.Attr{
  415. Name: xml.Name{Space: NameSpaceXML, Local: "space"},
  416. Value: "preserve",
  417. }
  418. }
  419. }
  420. xlsx.SheetData.Row[xAxis].C[yAxis].S = f.prepareCellStyle(xlsx, cell, xlsx.SheetData.Row[xAxis].C[yAxis].S)
  421. xlsx.SheetData.Row[xAxis].C[yAxis].T = "str"
  422. xlsx.SheetData.Row[xAxis].C[yAxis].V = value
  423. }
  424. // SetCellDefault provides function to set string type value of a cell as
  425. // default format without escaping the cell.
  426. func (f *File) SetCellDefault(sheet, axis, value string) {
  427. xlsx := f.workSheetReader(sheet)
  428. axis = f.mergeCellsParser(xlsx, axis)
  429. col := string(strings.Map(letterOnlyMapF, axis))
  430. row, err := strconv.Atoi(strings.Map(intOnlyMapF, axis))
  431. if err != nil {
  432. return
  433. }
  434. xAxis := row - 1
  435. yAxis := TitleToNumber(col)
  436. rows := xAxis + 1
  437. cell := yAxis + 1
  438. completeRow(xlsx, rows, cell)
  439. completeCol(xlsx, rows, cell)
  440. xlsx.SheetData.Row[xAxis].C[yAxis].S = f.prepareCellStyle(xlsx, cell, xlsx.SheetData.Row[xAxis].C[yAxis].S)
  441. xlsx.SheetData.Row[xAxis].C[yAxis].T = ""
  442. xlsx.SheetData.Row[xAxis].C[yAxis].V = value
  443. }
  444. // checkCellInArea provides function to determine if a given coordinate is
  445. // within an area.
  446. func checkCellInArea(cell, area string) bool {
  447. cell = strings.ToUpper(cell)
  448. area = strings.ToUpper(area)
  449. ref := strings.Split(area, ":")
  450. from := ref[0]
  451. to := ref[1]
  452. col, row := getCellColRow(cell)
  453. fromCol, fromRow := getCellColRow(from)
  454. toCol, toRow := getCellColRow(to)
  455. return axisLowerOrEqualThan(fromCol, col) && axisLowerOrEqualThan(col, toCol) && axisLowerOrEqualThan(fromRow, row) && axisLowerOrEqualThan(row, toRow)
  456. }