cell.go 16 KB

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