cell.go 17 KB

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