cell.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  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 := xlsx.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. The below is example for external link.
  321. //
  322. // err := xlsx.SetCellHyperLink("Sheet1", "A3", "https://github.com/360EntSecGroup-Skylar/excelize", "External")
  323. // // Set underline and font color style for the cell.
  324. // style, err := xlsx.NewStyle(`{"font":{"color":"#1265BE","underline":"single"}}`)
  325. // err = xlsx.SetCellStyle("Sheet1", "A3", "A3", style)
  326. //
  327. // A this is another example for "Location":
  328. //
  329. // err := xlsx.SetCellHyperLink("Sheet1", "A3", "Sheet1!A40", "Location")
  330. //
  331. func (f *File) SetCellHyperLink(sheet, axis, link, linkType string) error {
  332. // Check for correct cell name
  333. if _, _, err := SplitCellName(axis); err != nil {
  334. return err
  335. }
  336. xlsx, err := f.workSheetReader(sheet)
  337. if err != nil {
  338. return err
  339. }
  340. axis, err = f.mergeCellsParser(xlsx, axis)
  341. if err != nil {
  342. return err
  343. }
  344. var linkData xlsxHyperlink
  345. switch linkType {
  346. case "External":
  347. linkData = xlsxHyperlink{
  348. Ref: axis,
  349. }
  350. rID := f.addSheetRelationships(sheet, SourceRelationshipHyperLink, link, linkType)
  351. linkData.RID = "rId" + strconv.Itoa(rID)
  352. case "Location":
  353. linkData = xlsxHyperlink{
  354. Ref: axis,
  355. Location: link,
  356. }
  357. default:
  358. return fmt.Errorf("invalid link type %q", linkType)
  359. }
  360. if xlsx.Hyperlinks == nil {
  361. xlsx.Hyperlinks = new(xlsxHyperlinks)
  362. }
  363. xlsx.Hyperlinks.Hyperlink = append(xlsx.Hyperlinks.Hyperlink, linkData)
  364. return nil
  365. }
  366. // MergeCell provides a function to merge cells by given coordinate area and
  367. // sheet name. For example create a merged cell of D3:E9 on Sheet1:
  368. //
  369. // err := xlsx.MergeCell("Sheet1", "D3", "E9")
  370. //
  371. // If you create a merged cell that overlaps with another existing merged cell,
  372. // those merged cells that already exist will be removed.
  373. func (f *File) MergeCell(sheet, hcell, vcell string) error {
  374. hcol, hrow, err := CellNameToCoordinates(hcell)
  375. if err != nil {
  376. return err
  377. }
  378. vcol, vrow, err := CellNameToCoordinates(vcell)
  379. if err != nil {
  380. return err
  381. }
  382. if hcol == vcol && hrow == vrow {
  383. return err
  384. }
  385. // Correct the coordinate area, such correct C1:B3 to B1:C3.
  386. if vcol < hcol {
  387. hcol, vcol = vcol, hcol
  388. }
  389. if vrow < hrow {
  390. hrow, vrow = vrow, hrow
  391. }
  392. hcell, _ = CoordinatesToCellName(hcol, hrow)
  393. vcell, _ = CoordinatesToCellName(vcol, vrow)
  394. xlsx, err := f.workSheetReader(sheet)
  395. if err != nil {
  396. return err
  397. }
  398. if xlsx.MergeCells != nil {
  399. ref := hcell + ":" + vcell
  400. // Delete the merged cells of the overlapping area.
  401. for _, cellData := range xlsx.MergeCells.Cells {
  402. cc := strings.Split(cellData.Ref, ":")
  403. if len(cc) != 2 {
  404. return fmt.Errorf("invalid area %q", cellData.Ref)
  405. }
  406. c1, _ := checkCellInArea(hcell, cellData.Ref)
  407. c2, _ := checkCellInArea(vcell, cellData.Ref)
  408. c3, _ := checkCellInArea(cc[0], ref)
  409. c4, _ := checkCellInArea(cc[1], ref)
  410. if !(!c1 && !c2 && !c3 && !c4) {
  411. return nil
  412. }
  413. }
  414. xlsx.MergeCells.Cells = append(xlsx.MergeCells.Cells, &xlsxMergeCell{Ref: ref})
  415. } else {
  416. xlsx.MergeCells = &xlsxMergeCells{Cells: []*xlsxMergeCell{{Ref: hcell + ":" + vcell}}}
  417. }
  418. return err
  419. }
  420. // SetSheetRow writes an array to row by given worksheet name, starting
  421. // coordinate and a pointer to array type 'slice'. For example, writes an
  422. // array to row 6 start with the cell B6 on Sheet1:
  423. //
  424. // err := xlsx.SetSheetRow("Sheet1", "B6", &[]interface{}{"1", nil, 2})
  425. //
  426. func (f *File) SetSheetRow(sheet, axis string, slice interface{}) error {
  427. col, row, err := CellNameToCoordinates(axis)
  428. if err != nil {
  429. return err
  430. }
  431. // Make sure 'slice' is a Ptr to Slice
  432. v := reflect.ValueOf(slice)
  433. if v.Kind() != reflect.Ptr || v.Elem().Kind() != reflect.Slice {
  434. return errors.New("pointer to slice expected")
  435. }
  436. v = v.Elem()
  437. for i := 0; i < v.Len(); i++ {
  438. cell, err := CoordinatesToCellName(col+i, row)
  439. // Error should never happens here. But keep ckecking to early detect regresions
  440. // if it will be introduced in furure
  441. if err != nil {
  442. return err
  443. }
  444. f.SetCellValue(sheet, cell, v.Index(i).Interface())
  445. }
  446. return err
  447. }
  448. // getCellInfo does common preparation for all SetCell* methods.
  449. func (f *File) prepareCell(xlsx *xlsxWorksheet, sheet, cell string) (*xlsxC, int, int, error) {
  450. var err error
  451. cell, err = f.mergeCellsParser(xlsx, cell)
  452. if err != nil {
  453. return nil, 0, 0, err
  454. }
  455. col, row, err := CellNameToCoordinates(cell)
  456. if err != nil {
  457. return nil, 0, 0, err
  458. }
  459. prepareSheetXML(xlsx, col, row)
  460. return &xlsx.SheetData.Row[row-1].C[col-1], col, row, err
  461. }
  462. // getCellStringFunc does common value extraction workflow for all GetCell*
  463. // methods. Passed function implements specific part of required logic.
  464. func (f *File) getCellStringFunc(sheet, axis string, fn func(x *xlsxWorksheet, c *xlsxC) (string, bool, error)) (string, error) {
  465. xlsx, err := f.workSheetReader(sheet)
  466. if err != nil {
  467. return "", err
  468. }
  469. axis, err = f.mergeCellsParser(xlsx, axis)
  470. if err != nil {
  471. return "", err
  472. }
  473. _, row, err := CellNameToCoordinates(axis)
  474. if err != nil {
  475. return "", err
  476. }
  477. lastRowNum := 0
  478. if l := len(xlsx.SheetData.Row); l > 0 {
  479. lastRowNum = xlsx.SheetData.Row[l-1].R
  480. }
  481. // keep in mind: row starts from 1
  482. if row > lastRowNum {
  483. return "", nil
  484. }
  485. for rowIdx := range xlsx.SheetData.Row {
  486. rowData := &xlsx.SheetData.Row[rowIdx]
  487. if rowData.R != row {
  488. continue
  489. }
  490. for colIdx := range rowData.C {
  491. colData := &rowData.C[colIdx]
  492. if axis != colData.R {
  493. continue
  494. }
  495. val, ok, err := fn(xlsx, colData)
  496. if err != nil {
  497. return "", err
  498. }
  499. if ok {
  500. return val, nil
  501. }
  502. }
  503. }
  504. return "", nil
  505. }
  506. // formattedValue provides a function to returns a value after formatted. If
  507. // it is possible to apply a format to the cell value, it will do so, if not
  508. // then an error will be returned, along with the raw value of the cell.
  509. func (f *File) formattedValue(s int, v string) string {
  510. if s == 0 {
  511. return v
  512. }
  513. styleSheet := f.stylesReader()
  514. ok := builtInNumFmtFunc[styleSheet.CellXfs.Xf[s].NumFmtID]
  515. if ok != nil {
  516. return ok(styleSheet.CellXfs.Xf[s].NumFmtID, v)
  517. }
  518. return v
  519. }
  520. // prepareCellStyle provides a function to prepare style index of cell in
  521. // worksheet by given column index and style index.
  522. func (f *File) prepareCellStyle(xlsx *xlsxWorksheet, col, style int) int {
  523. if xlsx.Cols != nil && style == 0 {
  524. for _, c := range xlsx.Cols.Col {
  525. if c.Min <= col && col <= c.Max {
  526. style = c.Style
  527. }
  528. }
  529. }
  530. return style
  531. }
  532. // mergeCellsParser provides a function to check merged cells in worksheet by
  533. // given axis.
  534. func (f *File) mergeCellsParser(xlsx *xlsxWorksheet, axis string) (string, error) {
  535. axis = strings.ToUpper(axis)
  536. if xlsx.MergeCells != nil {
  537. for i := 0; i < len(xlsx.MergeCells.Cells); i++ {
  538. ok, err := checkCellInArea(axis, xlsx.MergeCells.Cells[i].Ref)
  539. if err != nil {
  540. return axis, err
  541. }
  542. if ok {
  543. axis = strings.Split(xlsx.MergeCells.Cells[i].Ref, ":")[0]
  544. }
  545. }
  546. }
  547. return axis, nil
  548. }
  549. // checkCellInArea provides a function to determine if a given coordinate is
  550. // within an area.
  551. func checkCellInArea(cell, area string) (bool, error) {
  552. col, row, err := CellNameToCoordinates(cell)
  553. if err != nil {
  554. return false, err
  555. }
  556. rng := strings.Split(area, ":")
  557. if len(rng) != 2 {
  558. return false, err
  559. }
  560. firstCol, firstRow, _ := CellNameToCoordinates(rng[0])
  561. lastCol, lastRow, _ := CellNameToCoordinates(rng[1])
  562. return col >= firstCol && col <= lastCol && row >= firstRow && row <= lastRow, err
  563. }
  564. // getSharedForumula find a cell contains the same formula as another cell,
  565. // the "shared" value can be used for the t attribute and the si attribute can
  566. // be used to refer to the cell containing the formula. Two formulas are
  567. // considered to be the same when their respective representations in
  568. // R1C1-reference notation, are the same.
  569. //
  570. // Note that this function not validate ref tag to check the cell if or not in
  571. // allow area, and always return origin shared formula.
  572. func getSharedForumula(xlsx *xlsxWorksheet, si string) string {
  573. for _, r := range xlsx.SheetData.Row {
  574. for _, c := range r.C {
  575. if c.F != nil && c.F.Ref != "" && c.F.T == STCellFormulaTypeShared && c.F.Si == si {
  576. return c.F.Content
  577. }
  578. }
  579. }
  580. return ""
  581. }