cell.go 14 KB

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