cell.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. // Copyright 2016 - 2019 The excelize Authors. All rights reserved. Use of
  2. // this source code is governed by a BSD-style license that can be found in
  3. // the LICENSE file.
  4. //
  5. // Package excelize providing a set of functions that allow you to write to
  6. // and read from XLSX files. Support reads and writes XLSX file generated by
  7. // Microsoft Excel™ 2007 and later. Support save file without losing original
  8. // charts of XLSX. This library needs Go version 1.8 or later.
  9. package excelize
  10. import (
  11. "encoding/xml"
  12. "errors"
  13. "fmt"
  14. "reflect"
  15. "strconv"
  16. "strings"
  17. "time"
  18. )
  19. const (
  20. // STCellFormulaTypeArray defined the formula is an array formula.
  21. STCellFormulaTypeArray = "array"
  22. // STCellFormulaTypeDataTable defined the formula is a data table formula.
  23. STCellFormulaTypeDataTable = "dataTable"
  24. // STCellFormulaTypeNormal defined the formula is a regular cell formula.
  25. STCellFormulaTypeNormal = "normal"
  26. // STCellFormulaTypeShared defined the formula is part of a shared formula.
  27. STCellFormulaTypeShared = "shared"
  28. )
  29. // GetCellValue provides a function to get formatted value from cell by given
  30. // worksheet name and axis in XLSX file. If it is possible to apply a format
  31. // to the cell value, it will do so, if not then an error will be returned,
  32. // along with the raw value of the cell.
  33. func (f *File) GetCellValue(sheet, axis string) string {
  34. return f.getCellStringFunc(sheet, axis, func(x *xlsxWorksheet, c *xlsxC) (string, bool) {
  35. val, err := c.getValueFrom(f, f.sharedStringsReader())
  36. if err != nil {
  37. panic(err) // Fail fast to avoid future side effects!
  38. }
  39. return val, true
  40. })
  41. }
  42. // SetCellValue provides a function to set value of a cell. The following
  43. // shows the supported data types:
  44. //
  45. // int
  46. // int8
  47. // int16
  48. // int32
  49. // int64
  50. // uint
  51. // uint8
  52. // uint16
  53. // uint32
  54. // uint64
  55. // float32
  56. // float64
  57. // string
  58. // []byte
  59. // time.Duration
  60. // time.Time
  61. // bool
  62. // nil
  63. //
  64. // Note that default date format is m/d/yy h:mm of time.Time type value. You can
  65. // set numbers format by SetCellStyle() method.
  66. func (f *File) SetCellValue(sheet, axis string, value interface{}) {
  67. switch v := value.(type) {
  68. case int:
  69. f.SetCellInt(sheet, axis, v)
  70. case int8:
  71. f.SetCellInt(sheet, axis, int(v))
  72. case int16:
  73. f.SetCellInt(sheet, axis, int(v))
  74. case int32:
  75. f.SetCellInt(sheet, axis, int(v))
  76. case int64:
  77. f.SetCellInt(sheet, axis, int(v))
  78. case uint:
  79. f.SetCellInt(sheet, axis, int(v))
  80. case uint8:
  81. f.SetCellInt(sheet, axis, int(v))
  82. case uint16:
  83. f.SetCellInt(sheet, axis, int(v))
  84. case uint32:
  85. f.SetCellInt(sheet, axis, int(v))
  86. case uint64:
  87. f.SetCellInt(sheet, axis, int(v))
  88. case float32:
  89. f.SetCellFloat(sheet, axis, float64(v), -1, 32)
  90. case float64:
  91. f.SetCellFloat(sheet, axis, v, -1, 64)
  92. case string:
  93. f.SetCellStr(sheet, axis, v)
  94. case []byte:
  95. f.SetCellStr(sheet, axis, string(v))
  96. case time.Duration:
  97. f.SetCellDefault(sheet, axis, strconv.FormatFloat(v.Seconds()/86400.0, 'f', -1, 32))
  98. f.setDefaultTimeStyle(sheet, axis, 21)
  99. case time.Time:
  100. vv := timeToExcelTime(v)
  101. if vv > 0 {
  102. f.SetCellDefault(sheet, axis, strconv.FormatFloat(timeToExcelTime(v), 'f', -1, 64))
  103. f.setDefaultTimeStyle(sheet, axis, 22)
  104. } else {
  105. f.SetCellStr(sheet, axis, v.Format(time.RFC3339Nano))
  106. }
  107. case bool:
  108. f.SetCellBool(sheet, axis, v)
  109. case nil:
  110. f.SetCellStr(sheet, axis, "")
  111. default:
  112. f.SetCellStr(sheet, axis, fmt.Sprintf("%v", value))
  113. }
  114. }
  115. // SetCellInt provides a function to set int type value of a cell by given
  116. // worksheet name, cell coordinates and cell value.
  117. func (f *File) SetCellInt(sheet, axis string, value int) {
  118. xlsx := f.workSheetReader(sheet)
  119. cellData, col, _ := f.prepareCell(xlsx, sheet, axis)
  120. cellData.S = f.prepareCellStyle(xlsx, col, cellData.S)
  121. cellData.T = ""
  122. cellData.V = strconv.Itoa(value)
  123. }
  124. // SetCellBool provides a function to set bool type value of a cell by given
  125. // worksheet name, cell name and cell value.
  126. func (f *File) SetCellBool(sheet, axis string, value bool) {
  127. xlsx := f.workSheetReader(sheet)
  128. cellData, col, _ := f.prepareCell(xlsx, sheet, axis)
  129. cellData.S = f.prepareCellStyle(xlsx, col, cellData.S)
  130. cellData.T = "b"
  131. if value {
  132. cellData.V = "1"
  133. } else {
  134. cellData.V = "0"
  135. }
  136. }
  137. // SetCellFloat sets a floating point value into a cell. The prec parameter
  138. // specifies how many places after the decimal will be shown while -1 is a
  139. // special value that will use as many decimal places as necessary to
  140. // represent the number. bitSize is 32 or 64 depending on if a float32 or
  141. // float64 was originally used for the value. For Example:
  142. //
  143. // var x float32 = 1.325
  144. // f.SetCellFloat("Sheet1", "A1", float64(x), 2, 32)
  145. //
  146. func (f *File) SetCellFloat(sheet, axis string, value float64, prec, bitSize int) {
  147. xlsx := f.workSheetReader(sheet)
  148. cellData, col, _ := f.prepareCell(xlsx, sheet, axis)
  149. cellData.S = f.prepareCellStyle(xlsx, col, cellData.S)
  150. cellData.T = ""
  151. cellData.V = strconv.FormatFloat(value, 'f', prec, bitSize)
  152. }
  153. // SetCellStr provides a function to set string type value of a cell. Total
  154. // number of characters that a cell can contain 32767 characters.
  155. func (f *File) SetCellStr(sheet, axis, value string) {
  156. xlsx := f.workSheetReader(sheet)
  157. cellData, col, _ := f.prepareCell(xlsx, sheet, axis)
  158. // Leading space(s) character detection.
  159. if len(value) > 0 && value[0] == 32 {
  160. cellData.XMLSpace = xml.Attr{
  161. Name: xml.Name{Space: NameSpaceXML, Local: "space"},
  162. Value: "preserve",
  163. }
  164. }
  165. cellData.S = f.prepareCellStyle(xlsx, col, cellData.S)
  166. cellData.T = "str"
  167. cellData.V = value
  168. }
  169. // SetCellDefault provides a function to set string type value of a cell as
  170. // default format without escaping the cell.
  171. func (f *File) SetCellDefault(sheet, axis, value string) {
  172. xlsx := f.workSheetReader(sheet)
  173. cellData, col, _ := f.prepareCell(xlsx, sheet, axis)
  174. cellData.S = f.prepareCellStyle(xlsx, col, cellData.S)
  175. cellData.T = ""
  176. cellData.V = value
  177. }
  178. // GetCellFormula provides a function to get formula from cell by given
  179. // worksheet name and axis in XLSX file.
  180. func (f *File) GetCellFormula(sheet, axis string) string {
  181. return f.getCellStringFunc(sheet, axis, func(x *xlsxWorksheet, c *xlsxC) (string, bool) {
  182. if c.F == nil {
  183. return "", false
  184. }
  185. if c.F.T == STCellFormulaTypeShared {
  186. return getSharedForumula(x, c.F.Si), true
  187. }
  188. return c.F.Content, true
  189. })
  190. }
  191. // SetCellFormula provides a function to set cell formula by given string and
  192. // worksheet name.
  193. func (f *File) SetCellFormula(sheet, axis, formula string) {
  194. xlsx := f.workSheetReader(sheet)
  195. cellData, _, _ := f.prepareCell(xlsx, sheet, axis)
  196. if formula == "" {
  197. cellData.F = nil
  198. f.deleteCalcChain(axis)
  199. return
  200. }
  201. if cellData.F != nil {
  202. cellData.F.Content = formula
  203. } else {
  204. cellData.F = &xlsxF{Content: formula}
  205. }
  206. }
  207. // GetCellHyperLink provides a function to get cell hyperlink by given
  208. // worksheet name and axis. Boolean type value link will be ture if the cell
  209. // has a hyperlink and the target is the address of the hyperlink. Otherwise,
  210. // the value of link will be false and the value of the target will be a blank
  211. // string. For example get hyperlink of Sheet1!H6:
  212. //
  213. // link, target := xlsx.GetCellHyperLink("Sheet1", "H6")
  214. //
  215. func (f *File) GetCellHyperLink(sheet, axis string) (bool, string) {
  216. // Check for correct cell name
  217. if _, _, err := SplitCellName(axis); err != nil {
  218. panic(err) // Fail fast to avoid possible future side effects
  219. }
  220. xlsx := f.workSheetReader(sheet)
  221. axis = f.mergeCellsParser(xlsx, axis)
  222. if xlsx.Hyperlinks != nil {
  223. for _, link := range xlsx.Hyperlinks.Hyperlink {
  224. if link.Ref == axis {
  225. if link.RID != "" {
  226. return true, f.getSheetRelationshipsTargetByID(sheet, link.RID)
  227. }
  228. return true, link.Location
  229. }
  230. }
  231. }
  232. return false, ""
  233. }
  234. // SetCellHyperLink provides a function to set cell hyperlink by given
  235. // worksheet name and link URL address. LinkType defines two types of
  236. // hyperlink "External" for web site or "Location" for moving to one of cell
  237. // in this workbook. The below is example for external link.
  238. //
  239. // xlsx.SetCellHyperLink("Sheet1", "A3", "https://github.com/360EntSecGroup-Skylar/excelize", "External")
  240. // // Set underline and font color style for the cell.
  241. // style, _ := xlsx.NewStyle(`{"font":{"color":"#1265BE","underline":"single"}}`)
  242. // xlsx.SetCellStyle("Sheet1", "A3", "A3", style)
  243. //
  244. // A this is another example for "Location":
  245. //
  246. // xlsx.SetCellHyperLink("Sheet1", "A3", "Sheet1!A40", "Location")
  247. //
  248. func (f *File) SetCellHyperLink(sheet, axis, link, linkType string) {
  249. // Check for correct cell name
  250. if _, _, err := SplitCellName(axis); err != nil {
  251. panic(err) // Fail fast to avoid possible future side effects
  252. }
  253. xlsx := f.workSheetReader(sheet)
  254. axis = f.mergeCellsParser(xlsx, axis)
  255. var linkData xlsxHyperlink
  256. switch linkType {
  257. case "External":
  258. linkData = xlsxHyperlink{
  259. Ref: axis,
  260. }
  261. rID := f.addSheetRelationships(sheet, SourceRelationshipHyperLink, link, linkType)
  262. linkData.RID = "rId" + strconv.Itoa(rID)
  263. case "Location":
  264. linkData = xlsxHyperlink{
  265. Ref: axis,
  266. Location: link,
  267. }
  268. default:
  269. panic(fmt.Errorf("invalid link type %q", linkType))
  270. }
  271. if xlsx.Hyperlinks == nil {
  272. xlsx.Hyperlinks = new(xlsxHyperlinks)
  273. }
  274. xlsx.Hyperlinks.Hyperlink = append(xlsx.Hyperlinks.Hyperlink, linkData)
  275. }
  276. // MergeCell provides a function to merge cells by given coordinate area and
  277. // sheet name. For example create a merged cell of D3:E9 on Sheet1:
  278. //
  279. // xlsx.MergeCell("Sheet1", "D3", "E9")
  280. //
  281. // If you create a merged cell that overlaps with another existing merged cell,
  282. // those merged cells that already exist will be removed.
  283. func (f *File) MergeCell(sheet, hcell, vcell string) {
  284. hcol, hrow, err := CellNameToCoordinates(hcell)
  285. if err != nil {
  286. panic(err)
  287. }
  288. vcol, vrow, err := CellNameToCoordinates(vcell)
  289. if err != nil {
  290. panic(err)
  291. }
  292. if hcol == vcol && hrow == vrow {
  293. return
  294. }
  295. if vcol < hcol {
  296. hcol, vcol = vcol, hcol
  297. }
  298. if vrow < hrow {
  299. hrow, vrow = vrow, hrow
  300. }
  301. hcell, _ = CoordinatesToCellName(hcol, hrow)
  302. vcell, _ = CoordinatesToCellName(vcol, vrow)
  303. xlsx := f.workSheetReader(sheet)
  304. if xlsx.MergeCells != nil {
  305. ref := hcell + ":" + vcell
  306. cells := make([]*xlsxMergeCell, 0, len(xlsx.MergeCells.Cells))
  307. // Delete the merged cells of the overlapping area.
  308. for _, cellData := range xlsx.MergeCells.Cells {
  309. cc := strings.Split(cellData.Ref, ":")
  310. if len(cc) != 2 {
  311. panic(fmt.Errorf("invalid area %q", cellData.Ref))
  312. }
  313. if !checkCellInArea(hcell, cellData.Ref) && !checkCellInArea(vcell, cellData.Ref) &&
  314. !checkCellInArea(cc[0], ref) && !checkCellInArea(cc[1], ref) {
  315. cells = append(cells, cellData)
  316. }
  317. }
  318. cells = append(xlsx.MergeCells.Cells, &xlsxMergeCell{Ref: ref})
  319. xlsx.MergeCells.Cells = cells
  320. } else {
  321. xlsx.MergeCells = &xlsxMergeCells{Cells: []*xlsxMergeCell{{Ref: hcell + ":" + vcell}}}
  322. }
  323. }
  324. // SetSheetRow writes an array to row by given worksheet name, starting
  325. // coordinate and a pointer to array type 'slice'. For example, writes an
  326. // array to row 6 start with the cell B6 on Sheet1:
  327. //
  328. // xlsx.SetSheetRow("Sheet1", "B6", &[]interface{}{"1", nil, 2})
  329. //
  330. func (f *File) SetSheetRow(sheet, axis string, slice interface{}) {
  331. col, row, err := CellNameToCoordinates(axis)
  332. if err != nil {
  333. panic(err) // Fail fast to avoid future side effects!
  334. }
  335. // Make sure 'slice' is a Ptr to Slice
  336. v := reflect.ValueOf(slice)
  337. if v.Kind() != reflect.Ptr || v.Elem().Kind() != reflect.Slice {
  338. panic(errors.New("pointer to slice expected")) // Fail fast to avoid future side effects!
  339. }
  340. v = v.Elem()
  341. for i := 0; i < v.Len(); i++ {
  342. cell, err := CoordinatesToCellName(col+i, row)
  343. // Error should never happens here. But keep ckecking to early detect regresions
  344. // if it will be introduced in furure
  345. if err != nil {
  346. panic(err) // Fail fast to avoid future side effects!
  347. }
  348. f.SetCellValue(sheet, cell, v.Index(i).Interface())
  349. }
  350. }
  351. // getCellInfo does common preparation for all SetCell* methods.
  352. func (f *File) prepareCell(xlsx *xlsxWorksheet, sheet, cell string) (*xlsxC, int, int) {
  353. cell = f.mergeCellsParser(xlsx, cell)
  354. col, row, err := CellNameToCoordinates(cell)
  355. if err != nil {
  356. panic(err) // Fail fast and prevent future side effects
  357. }
  358. prepareSheetXML(xlsx, col, row)
  359. return &xlsx.SheetData.Row[row-1].C[col-1], col, row
  360. }
  361. // getCellStringFunc does common value extraction workflow for all GetCell* methods.
  362. // Passed function implements specific part of required logic.
  363. func (f *File) getCellStringFunc(sheet, axis string, fn func(x *xlsxWorksheet, c *xlsxC) (string, bool)) string {
  364. xlsx := f.workSheetReader(sheet)
  365. axis = f.mergeCellsParser(xlsx, axis)
  366. _, row, err := CellNameToCoordinates(axis)
  367. if err != nil {
  368. panic(err) // Fail fast to avoid future side effects!
  369. }
  370. lastRowNum := 0
  371. if l := len(xlsx.SheetData.Row); l > 0 {
  372. lastRowNum = xlsx.SheetData.Row[l-1].R
  373. }
  374. // keep in mind: row starts from 1
  375. if row > lastRowNum {
  376. return ""
  377. }
  378. for rowIdx := range xlsx.SheetData.Row {
  379. rowData := &xlsx.SheetData.Row[rowIdx]
  380. if rowData.R != row {
  381. continue
  382. }
  383. for colIdx := range rowData.C {
  384. colData := &rowData.C[colIdx]
  385. if axis != colData.R {
  386. continue
  387. }
  388. if val, ok := fn(xlsx, colData); ok {
  389. return val
  390. }
  391. }
  392. }
  393. return ""
  394. }
  395. // formattedValue provides a function to returns a value after formatted. If
  396. // it is possible to apply a format to the cell value, it will do so, if not
  397. // then an error will be returned, along with the raw value of the cell.
  398. func (f *File) formattedValue(s int, v string) string {
  399. if s == 0 {
  400. return v
  401. }
  402. styleSheet := f.stylesReader()
  403. ok := builtInNumFmtFunc[styleSheet.CellXfs.Xf[s].NumFmtID]
  404. if ok != nil {
  405. return ok(styleSheet.CellXfs.Xf[s].NumFmtID, v)
  406. }
  407. return v
  408. }
  409. // prepareCellStyle provides a function to prepare style index of cell in
  410. // worksheet by given column index and style index.
  411. func (f *File) prepareCellStyle(xlsx *xlsxWorksheet, col, style int) int {
  412. if xlsx.Cols != nil && style == 0 {
  413. for _, c := range xlsx.Cols.Col {
  414. if c.Min <= col && col <= c.Max {
  415. style = c.Style
  416. }
  417. }
  418. }
  419. return style
  420. }
  421. // mergeCellsParser provides a function to check merged cells in worksheet by
  422. // given axis.
  423. func (f *File) mergeCellsParser(xlsx *xlsxWorksheet, axis string) string {
  424. axis = strings.ToUpper(axis)
  425. if xlsx.MergeCells != nil {
  426. for i := 0; i < len(xlsx.MergeCells.Cells); i++ {
  427. if checkCellInArea(axis, xlsx.MergeCells.Cells[i].Ref) {
  428. axis = strings.Split(xlsx.MergeCells.Cells[i].Ref, ":")[0]
  429. }
  430. }
  431. }
  432. return axis
  433. }
  434. // checkCellInArea provides a function to determine if a given coordinate is
  435. // within an area.
  436. func checkCellInArea(cell, area string) bool {
  437. col, row, err := CellNameToCoordinates(cell)
  438. if err != nil {
  439. panic(err)
  440. }
  441. rng := strings.Split(area, ":")
  442. if len(rng) != 2 {
  443. return false
  444. }
  445. firstCol, firtsRow, _ := CellNameToCoordinates(rng[0])
  446. lastCol, lastRow, _ := CellNameToCoordinates(rng[1])
  447. return col >= firstCol && col <= lastCol && row >= firtsRow && row <= lastRow
  448. }
  449. // getSharedForumula find a cell contains the same formula as another cell,
  450. // the "shared" value can be used for the t attribute and the si attribute can
  451. // be used to refer to the cell containing the formula. Two formulas are
  452. // considered to be the same when their respective representations in
  453. // R1C1-reference notation, are the same.
  454. //
  455. // Note that this function not validate ref tag to check the cell if or not in
  456. // allow area, and always return origin shared formula.
  457. func getSharedForumula(xlsx *xlsxWorksheet, si string) string {
  458. for _, r := range xlsx.SheetData.Row {
  459. for _, c := range r.C {
  460. if c.F != nil && c.F.Ref != "" && c.F.T == STCellFormulaTypeShared && c.F.Si == si {
  461. return c.F.Content
  462. }
  463. }
  464. }
  465. return ""
  466. }