cell.go 13 KB

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