cell.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  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, error) {
  34. return f.getCellStringFunc(sheet, axis, func(x *xlsxWorksheet, c *xlsxC) (string, bool, error) {
  35. val, err := c.getValueFrom(f, f.sharedStringsReader())
  36. if err != nil {
  37. return val, false, err
  38. }
  39. return val, true, err
  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{}) error {
  67. var err error
  68. switch v := value.(type) {
  69. case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
  70. err = f.setCellIntFunc(sheet, axis, v)
  71. case float32:
  72. err = f.SetCellFloat(sheet, axis, float64(v), -1, 32)
  73. case float64:
  74. err = f.SetCellFloat(sheet, axis, v, -1, 64)
  75. case string:
  76. err = f.SetCellStr(sheet, axis, v)
  77. case []byte:
  78. err = f.SetCellStr(sheet, axis, string(v))
  79. case time.Duration:
  80. err = f.SetCellDefault(sheet, axis, strconv.FormatFloat(v.Seconds()/86400.0, 'f', -1, 32))
  81. if err != nil {
  82. return err
  83. }
  84. err = f.setDefaultTimeStyle(sheet, axis, 21)
  85. case time.Time:
  86. err = f.setCellTimeFunc(sheet, axis, v)
  87. case bool:
  88. err = f.SetCellBool(sheet, axis, v)
  89. case nil:
  90. err = f.SetCellStr(sheet, axis, "")
  91. default:
  92. err = f.SetCellStr(sheet, axis, fmt.Sprintf("%v", value))
  93. }
  94. return err
  95. }
  96. // setCellIntFunc is a wrapper of SetCellInt.
  97. func (f *File) setCellIntFunc(sheet, axis string, value interface{}) error {
  98. var err error
  99. switch v := value.(type) {
  100. case int:
  101. err = f.SetCellInt(sheet, axis, v)
  102. case int8:
  103. err = f.SetCellInt(sheet, axis, int(v))
  104. case int16:
  105. err = f.SetCellInt(sheet, axis, int(v))
  106. case int32:
  107. err = f.SetCellInt(sheet, axis, int(v))
  108. case int64:
  109. err = f.SetCellInt(sheet, axis, int(v))
  110. case uint:
  111. err = f.SetCellInt(sheet, axis, int(v))
  112. case uint8:
  113. err = f.SetCellInt(sheet, axis, int(v))
  114. case uint16:
  115. err = f.SetCellInt(sheet, axis, int(v))
  116. case uint32:
  117. err = f.SetCellInt(sheet, axis, int(v))
  118. case uint64:
  119. err = f.SetCellInt(sheet, axis, int(v))
  120. }
  121. return err
  122. }
  123. // setCellTimeFunc provides a method to process time type of value for
  124. // SetCellValue.
  125. func (f *File) setCellTimeFunc(sheet, axis string, value time.Time) error {
  126. excelTime, err := timeToExcelTime(value)
  127. if err != nil {
  128. return err
  129. }
  130. if excelTime > 0 {
  131. err = f.SetCellDefault(sheet, axis, strconv.FormatFloat(excelTime, 'f', -1, 64))
  132. if err != nil {
  133. return err
  134. }
  135. err = f.setDefaultTimeStyle(sheet, axis, 22)
  136. if err != nil {
  137. return err
  138. }
  139. } else {
  140. err = f.SetCellStr(sheet, axis, value.Format(time.RFC3339Nano))
  141. if err != nil {
  142. return err
  143. }
  144. }
  145. return err
  146. }
  147. // SetCellInt provides a function to set int type value of a cell by given
  148. // worksheet name, cell coordinates and cell value.
  149. func (f *File) SetCellInt(sheet, axis string, value int) error {
  150. xlsx, err := f.workSheetReader(sheet)
  151. if err != nil {
  152. return err
  153. }
  154. cellData, col, _, err := f.prepareCell(xlsx, sheet, axis)
  155. if err != nil {
  156. return err
  157. }
  158. cellData.S = f.prepareCellStyle(xlsx, col, cellData.S)
  159. cellData.T = ""
  160. cellData.V = strconv.Itoa(value)
  161. return err
  162. }
  163. // SetCellBool provides a function to set bool type value of a cell by given
  164. // worksheet name, cell name and cell value.
  165. func (f *File) SetCellBool(sheet, axis string, value bool) error {
  166. xlsx, err := f.workSheetReader(sheet)
  167. if err != nil {
  168. return err
  169. }
  170. cellData, col, _, err := f.prepareCell(xlsx, sheet, axis)
  171. if err != nil {
  172. return err
  173. }
  174. cellData.S = f.prepareCellStyle(xlsx, col, cellData.S)
  175. cellData.T = "b"
  176. if value {
  177. cellData.V = "1"
  178. } else {
  179. cellData.V = "0"
  180. }
  181. return err
  182. }
  183. // SetCellFloat sets a floating point value into a cell. The prec parameter
  184. // specifies how many places after the decimal will be shown while -1 is a
  185. // special value that will use as many decimal places as necessary to
  186. // represent the number. bitSize is 32 or 64 depending on if a float32 or
  187. // float64 was originally used for the value. For Example:
  188. //
  189. // var x float32 = 1.325
  190. // f.SetCellFloat("Sheet1", "A1", float64(x), 2, 32)
  191. //
  192. func (f *File) SetCellFloat(sheet, axis string, value float64, prec, bitSize int) error {
  193. xlsx, err := f.workSheetReader(sheet)
  194. if err != nil {
  195. return err
  196. }
  197. cellData, col, _, err := f.prepareCell(xlsx, sheet, axis)
  198. if err != nil {
  199. return err
  200. }
  201. cellData.S = f.prepareCellStyle(xlsx, col, cellData.S)
  202. cellData.T = ""
  203. cellData.V = strconv.FormatFloat(value, 'f', prec, bitSize)
  204. return err
  205. }
  206. // SetCellStr provides a function to set string type value of a cell. Total
  207. // number of characters that a cell can contain 32767 characters.
  208. func (f *File) SetCellStr(sheet, axis, value string) error {
  209. xlsx, err := f.workSheetReader(sheet)
  210. if err != nil {
  211. return err
  212. }
  213. cellData, col, _, err := f.prepareCell(xlsx, sheet, axis)
  214. if err != nil {
  215. return err
  216. }
  217. if len(value) > 32767 {
  218. value = value[0:32767]
  219. }
  220. // Leading space(s) character detection.
  221. if len(value) > 0 && value[0] == 32 {
  222. cellData.XMLSpace = xml.Attr{
  223. Name: xml.Name{Space: NameSpaceXML, Local: "space"},
  224. Value: "preserve",
  225. }
  226. }
  227. cellData.S = f.prepareCellStyle(xlsx, col, cellData.S)
  228. cellData.T = "str"
  229. cellData.V = value
  230. return err
  231. }
  232. // SetCellDefault provides a function to set string type value of a cell as
  233. // default format without escaping the cell.
  234. func (f *File) SetCellDefault(sheet, axis, value string) error {
  235. xlsx, err := f.workSheetReader(sheet)
  236. if err != nil {
  237. return err
  238. }
  239. cellData, col, _, err := f.prepareCell(xlsx, sheet, axis)
  240. if err != nil {
  241. return err
  242. }
  243. cellData.S = f.prepareCellStyle(xlsx, col, cellData.S)
  244. cellData.T = ""
  245. cellData.V = value
  246. return err
  247. }
  248. // GetCellFormula provides a function to get formula from cell by given
  249. // worksheet name and axis in XLSX file.
  250. func (f *File) GetCellFormula(sheet, axis string) (string, error) {
  251. return f.getCellStringFunc(sheet, axis, func(x *xlsxWorksheet, c *xlsxC) (string, bool, error) {
  252. if c.F == nil {
  253. return "", false, nil
  254. }
  255. if c.F.T == STCellFormulaTypeShared {
  256. return getSharedForumula(x, c.F.Si), true, nil
  257. }
  258. return c.F.Content, true, nil
  259. })
  260. }
  261. // SetCellFormula provides a function to set cell formula by given string and
  262. // worksheet name.
  263. func (f *File) SetCellFormula(sheet, axis, formula string) error {
  264. xlsx, err := f.workSheetReader(sheet)
  265. if err != nil {
  266. return err
  267. }
  268. cellData, _, _, err := f.prepareCell(xlsx, sheet, axis)
  269. if err != nil {
  270. return err
  271. }
  272. if formula == "" {
  273. cellData.F = nil
  274. f.deleteCalcChain(f.GetSheetIndex(sheet), axis)
  275. return err
  276. }
  277. if cellData.F != nil {
  278. cellData.F.Content = formula
  279. } else {
  280. cellData.F = &xlsxF{Content: formula}
  281. }
  282. return err
  283. }
  284. // GetCellHyperLink provides a function to get cell hyperlink by given
  285. // worksheet name and axis. Boolean type value link will be ture if the cell
  286. // has a hyperlink and the target is the address of the hyperlink. Otherwise,
  287. // the value of link will be false and the value of the target will be a blank
  288. // string. For example get hyperlink of Sheet1!H6:
  289. //
  290. // link, target, err := f.GetCellHyperLink("Sheet1", "H6")
  291. //
  292. func (f *File) GetCellHyperLink(sheet, axis string) (bool, string, error) {
  293. // Check for correct cell name
  294. if _, _, err := SplitCellName(axis); err != nil {
  295. return false, "", err
  296. }
  297. xlsx, err := f.workSheetReader(sheet)
  298. if err != nil {
  299. return false, "", err
  300. }
  301. axis, err = f.mergeCellsParser(xlsx, axis)
  302. if err != nil {
  303. return false, "", err
  304. }
  305. if xlsx.Hyperlinks != nil {
  306. for _, link := range xlsx.Hyperlinks.Hyperlink {
  307. if link.Ref == axis {
  308. if link.RID != "" {
  309. return true, f.getSheetRelationshipsTargetByID(sheet, link.RID), err
  310. }
  311. return true, link.Location, err
  312. }
  313. }
  314. }
  315. return false, "", err
  316. }
  317. // SetCellHyperLink provides a function to set cell hyperlink by given
  318. // worksheet name and link URL address. LinkType defines two types of
  319. // hyperlink "External" for web site or "Location" for moving to one of cell
  320. // in this workbook. Maximum limit hyperlinks in a worksheet is 65530. The
  321. // below is example for external link.
  322. //
  323. // err := f.SetCellHyperLink("Sheet1", "A3", "https://github.com/360EntSecGroup-Skylar/excelize", "External")
  324. // // Set underline and font color style for the cell.
  325. // style, err := f.NewStyle(`{"font":{"color":"#1265BE","underline":"single"}}`)
  326. // err = f.SetCellStyle("Sheet1", "A3", "A3", style)
  327. //
  328. // A this is another example for "Location":
  329. //
  330. // err := f.SetCellHyperLink("Sheet1", "A3", "Sheet1!A40", "Location")
  331. //
  332. func (f *File) SetCellHyperLink(sheet, axis, link, linkType string) error {
  333. // Check for correct cell name
  334. if _, _, err := SplitCellName(axis); err != nil {
  335. return err
  336. }
  337. xlsx, err := f.workSheetReader(sheet)
  338. if err != nil {
  339. return err
  340. }
  341. axis, err = f.mergeCellsParser(xlsx, axis)
  342. if err != nil {
  343. return err
  344. }
  345. var linkData xlsxHyperlink
  346. if xlsx.Hyperlinks == nil {
  347. xlsx.Hyperlinks = new(xlsxHyperlinks)
  348. }
  349. if len(xlsx.Hyperlinks.Hyperlink) > 65529 {
  350. return errors.New("over maximum limit hyperlinks in a worksheet")
  351. }
  352. switch linkType {
  353. case "External":
  354. linkData = xlsxHyperlink{
  355. Ref: axis,
  356. }
  357. rID := f.addSheetRelationships(sheet, SourceRelationshipHyperLink, link, linkType)
  358. linkData.RID = "rId" + strconv.Itoa(rID)
  359. case "Location":
  360. linkData = xlsxHyperlink{
  361. Ref: axis,
  362. Location: link,
  363. }
  364. default:
  365. return fmt.Errorf("invalid link type %q", linkType)
  366. }
  367. xlsx.Hyperlinks.Hyperlink = append(xlsx.Hyperlinks.Hyperlink, linkData)
  368. return nil
  369. }
  370. // MergeCell provides a function to merge cells by given coordinate area and
  371. // sheet name. For example create a merged cell of D3:E9 on Sheet1:
  372. //
  373. // err := f.MergeCell("Sheet1", "D3", "E9")
  374. //
  375. // If you create a merged cell that overlaps with another existing merged cell,
  376. // those merged cells that already exist will be removed.
  377. func (f *File) MergeCell(sheet, hcell, vcell string) error {
  378. coordinates, err := f.areaRefToCoordinates(hcell + ":" + vcell)
  379. if err != nil {
  380. return err
  381. }
  382. x1, y1, x2, y2 := coordinates[0], coordinates[1], coordinates[2], coordinates[3]
  383. if x1 == x2 && y1 == y2 {
  384. return err
  385. }
  386. // Correct the coordinate area, such correct C1:B3 to B1:C3.
  387. if x2 < x1 {
  388. x1, x2 = x2, x1
  389. }
  390. if y2 < y1 {
  391. y1, y2 = y2, y1
  392. }
  393. hcell, _ = CoordinatesToCellName(x1, y1)
  394. vcell, _ = CoordinatesToCellName(x2, y2)
  395. xlsx, err := f.workSheetReader(sheet)
  396. if err != nil {
  397. return err
  398. }
  399. if xlsx.MergeCells != nil {
  400. ref := hcell + ":" + vcell
  401. // Delete the merged cells of the overlapping area.
  402. for _, cellData := range xlsx.MergeCells.Cells {
  403. cc := strings.Split(cellData.Ref, ":")
  404. if len(cc) != 2 {
  405. return fmt.Errorf("invalid area %q", cellData.Ref)
  406. }
  407. c1, _ := checkCellInArea(hcell, cellData.Ref)
  408. c2, _ := checkCellInArea(vcell, cellData.Ref)
  409. c3, _ := checkCellInArea(cc[0], ref)
  410. c4, _ := checkCellInArea(cc[1], ref)
  411. if !(!c1 && !c2 && !c3 && !c4) {
  412. return nil
  413. }
  414. }
  415. xlsx.MergeCells.Cells = append(xlsx.MergeCells.Cells, &xlsxMergeCell{Ref: ref})
  416. } else {
  417. xlsx.MergeCells = &xlsxMergeCells{Cells: []*xlsxMergeCell{{Ref: hcell + ":" + vcell}}}
  418. }
  419. return err
  420. }
  421. // SetSheetRow writes an array to row by given worksheet name, starting
  422. // coordinate and a pointer to array type 'slice'. For example, writes an
  423. // array to row 6 start with the cell B6 on Sheet1:
  424. //
  425. // err := f.SetSheetRow("Sheet1", "B6", &[]interface{}{"1", nil, 2})
  426. //
  427. func (f *File) SetSheetRow(sheet, axis string, slice interface{}) error {
  428. col, row, err := CellNameToCoordinates(axis)
  429. if err != nil {
  430. return err
  431. }
  432. // Make sure 'slice' is a Ptr to Slice
  433. v := reflect.ValueOf(slice)
  434. if v.Kind() != reflect.Ptr || v.Elem().Kind() != reflect.Slice {
  435. return errors.New("pointer to slice expected")
  436. }
  437. v = v.Elem()
  438. for i := 0; i < v.Len(); i++ {
  439. cell, err := CoordinatesToCellName(col+i, row)
  440. // Error should never happens here. But keep ckecking to early detect regresions
  441. // if it will be introduced in furure
  442. if err != nil {
  443. return err
  444. }
  445. f.SetCellValue(sheet, cell, v.Index(i).Interface())
  446. }
  447. return err
  448. }
  449. // getCellInfo does common preparation for all SetCell* methods.
  450. func (f *File) prepareCell(xlsx *xlsxWorksheet, sheet, cell string) (*xlsxC, int, int, error) {
  451. var err error
  452. cell, err = f.mergeCellsParser(xlsx, cell)
  453. if err != nil {
  454. return nil, 0, 0, err
  455. }
  456. col, row, err := CellNameToCoordinates(cell)
  457. if err != nil {
  458. return nil, 0, 0, err
  459. }
  460. prepareSheetXML(xlsx, col, row)
  461. return &xlsx.SheetData.Row[row-1].C[col-1], col, row, err
  462. }
  463. // getCellStringFunc does common value extraction workflow for all GetCell*
  464. // methods. Passed function implements specific part of required logic.
  465. func (f *File) getCellStringFunc(sheet, axis string, fn func(x *xlsxWorksheet, c *xlsxC) (string, bool, error)) (string, error) {
  466. xlsx, err := f.workSheetReader(sheet)
  467. if err != nil {
  468. return "", err
  469. }
  470. axis, err = f.mergeCellsParser(xlsx, axis)
  471. if err != nil {
  472. return "", err
  473. }
  474. _, row, err := CellNameToCoordinates(axis)
  475. if err != nil {
  476. return "", err
  477. }
  478. lastRowNum := 0
  479. if l := len(xlsx.SheetData.Row); l > 0 {
  480. lastRowNum = xlsx.SheetData.Row[l-1].R
  481. }
  482. // keep in mind: row starts from 1
  483. if row > lastRowNum {
  484. return "", nil
  485. }
  486. for rowIdx := range xlsx.SheetData.Row {
  487. rowData := &xlsx.SheetData.Row[rowIdx]
  488. if rowData.R != row {
  489. continue
  490. }
  491. for colIdx := range rowData.C {
  492. colData := &rowData.C[colIdx]
  493. if axis != colData.R {
  494. continue
  495. }
  496. val, ok, err := fn(xlsx, colData)
  497. if err != nil {
  498. return "", err
  499. }
  500. if ok {
  501. return val, nil
  502. }
  503. }
  504. }
  505. return "", nil
  506. }
  507. // formattedValue provides a function to returns a value after formatted. If
  508. // it is possible to apply a format to the cell value, it will do so, if not
  509. // then an error will be returned, along with the raw value of the cell.
  510. func (f *File) formattedValue(s int, v string) string {
  511. if s == 0 {
  512. return v
  513. }
  514. styleSheet := f.stylesReader()
  515. ok := builtInNumFmtFunc[styleSheet.CellXfs.Xf[s].NumFmtID]
  516. if ok != nil {
  517. return ok(styleSheet.CellXfs.Xf[s].NumFmtID, v)
  518. }
  519. return v
  520. }
  521. // prepareCellStyle provides a function to prepare style index of cell in
  522. // worksheet by given column index and style index.
  523. func (f *File) prepareCellStyle(xlsx *xlsxWorksheet, col, style int) int {
  524. if xlsx.Cols != nil && style == 0 {
  525. for _, c := range xlsx.Cols.Col {
  526. if c.Min <= col && col <= c.Max {
  527. style = c.Style
  528. }
  529. }
  530. }
  531. return style
  532. }
  533. // mergeCellsParser provides a function to check merged cells in worksheet by
  534. // given axis.
  535. func (f *File) mergeCellsParser(xlsx *xlsxWorksheet, axis string) (string, error) {
  536. axis = strings.ToUpper(axis)
  537. if xlsx.MergeCells != nil {
  538. for i := 0; i < len(xlsx.MergeCells.Cells); i++ {
  539. ok, err := checkCellInArea(axis, xlsx.MergeCells.Cells[i].Ref)
  540. if err != nil {
  541. return axis, err
  542. }
  543. if ok {
  544. axis = strings.Split(xlsx.MergeCells.Cells[i].Ref, ":")[0]
  545. }
  546. }
  547. }
  548. return axis, nil
  549. }
  550. // checkCellInArea provides a function to determine if a given coordinate is
  551. // within an area.
  552. func checkCellInArea(cell, area string) (bool, error) {
  553. col, row, err := CellNameToCoordinates(cell)
  554. if err != nil {
  555. return false, err
  556. }
  557. rng := strings.Split(area, ":")
  558. if len(rng) != 2 {
  559. return false, err
  560. }
  561. firstCol, firstRow, _ := CellNameToCoordinates(rng[0])
  562. lastCol, lastRow, _ := CellNameToCoordinates(rng[1])
  563. return col >= firstCol && col <= lastCol && row >= firstRow && row <= lastRow, err
  564. }
  565. // getSharedForumula find a cell contains the same formula as another cell,
  566. // the "shared" value can be used for the t attribute and the si attribute can
  567. // be used to refer to the cell containing the formula. Two formulas are
  568. // considered to be the same when their respective representations in
  569. // R1C1-reference notation, are the same.
  570. //
  571. // Note that this function not validate ref tag to check the cell if or not in
  572. // allow area, and always return origin shared formula.
  573. func getSharedForumula(xlsx *xlsxWorksheet, si string) string {
  574. for _, r := range xlsx.SheetData.Row {
  575. for _, c := range r.C {
  576. if c.F != nil && c.F.Ref != "" && c.F.T == STCellFormulaTypeShared && c.F.Si == si {
  577. return c.F.Content
  578. }
  579. }
  580. }
  581. return ""
  582. }