cell.go 12 KB

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