cell.go 16 KB

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