cell.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826
  1. // Copyright 2016 - 2020 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.10 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 specified
  43. // coordinates should not be in the first row of the table. The following
  44. // shows the supported data types:
  45. //
  46. // int
  47. // int8
  48. // int16
  49. // int32
  50. // int64
  51. // uint
  52. // uint8
  53. // uint16
  54. // uint32
  55. // uint64
  56. // float32
  57. // float64
  58. // string
  59. // []byte
  60. // time.Duration
  61. // time.Time
  62. // bool
  63. // nil
  64. //
  65. // Note that default date format is m/d/yy h:mm of time.Time type value. You can
  66. // set numbers format by SetCellStyle() method.
  67. func (f *File) SetCellValue(sheet, axis string, value interface{}) error {
  68. var err error
  69. switch v := value.(type) {
  70. case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
  71. err = f.setCellIntFunc(sheet, axis, v)
  72. case float32:
  73. err = f.SetCellFloat(sheet, axis, float64(v), -1, 32)
  74. case float64:
  75. err = f.SetCellFloat(sheet, axis, v, -1, 64)
  76. case string:
  77. err = f.SetCellStr(sheet, axis, v)
  78. case []byte:
  79. err = f.SetCellStr(sheet, axis, string(v))
  80. case time.Duration:
  81. _, d := setCellDuration(v)
  82. err = f.SetCellDefault(sheet, axis, d)
  83. if err != nil {
  84. return err
  85. }
  86. err = f.setDefaultTimeStyle(sheet, axis, 21)
  87. case time.Time:
  88. err = f.setCellTimeFunc(sheet, axis, v)
  89. case bool:
  90. err = f.SetCellBool(sheet, axis, v)
  91. case nil:
  92. err = f.SetCellStr(sheet, axis, "")
  93. default:
  94. err = f.SetCellStr(sheet, axis, fmt.Sprint(value))
  95. }
  96. return err
  97. }
  98. // setCellIntFunc is a wrapper of SetCellInt.
  99. func (f *File) setCellIntFunc(sheet, axis string, value interface{}) error {
  100. var err error
  101. switch v := value.(type) {
  102. case int:
  103. err = f.SetCellInt(sheet, axis, v)
  104. case int8:
  105. err = f.SetCellInt(sheet, axis, int(v))
  106. case int16:
  107. err = f.SetCellInt(sheet, axis, int(v))
  108. case int32:
  109. err = f.SetCellInt(sheet, axis, int(v))
  110. case int64:
  111. err = f.SetCellInt(sheet, axis, int(v))
  112. case uint:
  113. err = f.SetCellInt(sheet, axis, int(v))
  114. case uint8:
  115. err = f.SetCellInt(sheet, axis, int(v))
  116. case uint16:
  117. err = f.SetCellInt(sheet, axis, int(v))
  118. case uint32:
  119. err = f.SetCellInt(sheet, axis, int(v))
  120. case uint64:
  121. err = f.SetCellInt(sheet, axis, int(v))
  122. }
  123. return err
  124. }
  125. // setCellTimeFunc provides a method to process time type of value for
  126. // SetCellValue.
  127. func (f *File) setCellTimeFunc(sheet, axis string, value time.Time) error {
  128. xlsx, err := f.workSheetReader(sheet)
  129. if err != nil {
  130. return err
  131. }
  132. cellData, col, _, err := f.prepareCell(xlsx, sheet, axis)
  133. if err != nil {
  134. return err
  135. }
  136. cellData.S = f.prepareCellStyle(xlsx, col, cellData.S)
  137. var isNum bool
  138. cellData.T, cellData.V, isNum, err = setCellTime(value)
  139. if err != nil {
  140. return err
  141. }
  142. if isNum {
  143. err = f.setDefaultTimeStyle(sheet, axis, 22)
  144. if err != nil {
  145. return err
  146. }
  147. }
  148. return err
  149. }
  150. func setCellTime(value time.Time) (t string, b string, isNum bool, err error) {
  151. var excelTime float64
  152. excelTime, err = timeToExcelTime(value)
  153. if err != nil {
  154. return
  155. }
  156. isNum = excelTime > 0
  157. if isNum {
  158. t, b = setCellDefault(strconv.FormatFloat(excelTime, 'f', -1, 64))
  159. } else {
  160. t, b = setCellDefault(value.Format(time.RFC3339Nano))
  161. }
  162. return
  163. }
  164. func setCellDuration(value time.Duration) (t string, v string) {
  165. v = strconv.FormatFloat(value.Seconds()/86400.0, 'f', -1, 32)
  166. return
  167. }
  168. // SetCellInt provides a function to set int type value of a cell by given
  169. // worksheet name, cell coordinates and cell value.
  170. func (f *File) SetCellInt(sheet, axis string, value int) error {
  171. xlsx, err := f.workSheetReader(sheet)
  172. if err != nil {
  173. return err
  174. }
  175. cellData, col, _, err := f.prepareCell(xlsx, sheet, axis)
  176. if err != nil {
  177. return err
  178. }
  179. cellData.S = f.prepareCellStyle(xlsx, col, cellData.S)
  180. cellData.T, cellData.V = setCellInt(value)
  181. return err
  182. }
  183. func setCellInt(value int) (t string, v string) {
  184. v = strconv.Itoa(value)
  185. return
  186. }
  187. // SetCellBool provides a function to set bool type value of a cell by given
  188. // worksheet name, cell name and cell value.
  189. func (f *File) SetCellBool(sheet, axis string, value bool) error {
  190. xlsx, err := f.workSheetReader(sheet)
  191. if err != nil {
  192. return err
  193. }
  194. cellData, col, _, err := f.prepareCell(xlsx, sheet, axis)
  195. if err != nil {
  196. return err
  197. }
  198. cellData.S = f.prepareCellStyle(xlsx, col, cellData.S)
  199. cellData.T, cellData.V = setCellBool(value)
  200. return err
  201. }
  202. func setCellBool(value bool) (t string, v string) {
  203. t = "b"
  204. if value {
  205. v = "1"
  206. } else {
  207. v = "0"
  208. }
  209. return
  210. }
  211. // SetCellFloat sets a floating point value into a cell. The prec parameter
  212. // specifies how many places after the decimal will be shown while -1 is a
  213. // special value that will use as many decimal places as necessary to
  214. // represent the number. bitSize is 32 or 64 depending on if a float32 or
  215. // float64 was originally used for the value. For Example:
  216. //
  217. // var x float32 = 1.325
  218. // f.SetCellFloat("Sheet1", "A1", float64(x), 2, 32)
  219. //
  220. func (f *File) SetCellFloat(sheet, axis string, value float64, prec, bitSize int) error {
  221. xlsx, err := f.workSheetReader(sheet)
  222. if err != nil {
  223. return err
  224. }
  225. cellData, col, _, err := f.prepareCell(xlsx, sheet, axis)
  226. if err != nil {
  227. return err
  228. }
  229. cellData.S = f.prepareCellStyle(xlsx, col, cellData.S)
  230. cellData.T, cellData.V = setCellFloat(value, prec, bitSize)
  231. return err
  232. }
  233. func setCellFloat(value float64, prec, bitSize int) (t string, v string) {
  234. v = strconv.FormatFloat(value, 'f', prec, bitSize)
  235. return
  236. }
  237. // SetCellStr provides a function to set string type value of a cell. Total
  238. // number of characters that a cell can contain 32767 characters.
  239. func (f *File) SetCellStr(sheet, axis, value string) error {
  240. xlsx, err := f.workSheetReader(sheet)
  241. if err != nil {
  242. return err
  243. }
  244. cellData, col, _, err := f.prepareCell(xlsx, sheet, axis)
  245. if err != nil {
  246. return err
  247. }
  248. cellData.S = f.prepareCellStyle(xlsx, col, cellData.S)
  249. cellData.T, cellData.V, cellData.XMLSpace = setCellStr(value)
  250. return err
  251. }
  252. func setCellStr(value string) (t string, v string, ns xml.Attr) {
  253. if len(value) > 32767 {
  254. value = value[0:32767]
  255. }
  256. // Leading and ending space(s) character detection.
  257. if len(value) > 0 && (value[0] == 32 || value[len(value)-1] == 32) {
  258. ns = xml.Attr{
  259. Name: xml.Name{Space: NameSpaceXML, Local: "space"},
  260. Value: "preserve",
  261. }
  262. }
  263. t = "str"
  264. v = value
  265. return
  266. }
  267. // SetCellDefault provides a function to set string type value of a cell as
  268. // default format without escaping the cell.
  269. func (f *File) SetCellDefault(sheet, axis, value string) error {
  270. xlsx, err := f.workSheetReader(sheet)
  271. if err != nil {
  272. return err
  273. }
  274. cellData, col, _, err := f.prepareCell(xlsx, sheet, axis)
  275. if err != nil {
  276. return err
  277. }
  278. cellData.S = f.prepareCellStyle(xlsx, col, cellData.S)
  279. cellData.T, cellData.V = setCellDefault(value)
  280. return err
  281. }
  282. func setCellDefault(value string) (t string, v string) {
  283. v = value
  284. return
  285. }
  286. // GetCellFormula provides a function to get formula from cell by given
  287. // worksheet name and axis in XLSX file.
  288. func (f *File) GetCellFormula(sheet, axis string) (string, error) {
  289. return f.getCellStringFunc(sheet, axis, func(x *xlsxWorksheet, c *xlsxC) (string, bool, error) {
  290. if c.F == nil {
  291. return "", false, nil
  292. }
  293. if c.F.T == STCellFormulaTypeShared {
  294. return getSharedForumula(x, c.F.Si), true, nil
  295. }
  296. return c.F.Content, true, nil
  297. })
  298. }
  299. // FormulaOpts can be passed to SetCellFormula to use other formula types.
  300. type FormulaOpts struct {
  301. Type *string // Formula type
  302. Ref *string // Shared formula ref
  303. }
  304. // SetCellFormula provides a function to set cell formula by given string and
  305. // worksheet name.
  306. func (f *File) SetCellFormula(sheet, axis, formula string, opts ...FormulaOpts) error {
  307. xlsx, err := f.workSheetReader(sheet)
  308. if err != nil {
  309. return err
  310. }
  311. cellData, _, _, err := f.prepareCell(xlsx, sheet, axis)
  312. if err != nil {
  313. return err
  314. }
  315. if formula == "" {
  316. cellData.F = nil
  317. f.deleteCalcChain(f.GetSheetIndex(sheet), axis)
  318. return err
  319. }
  320. if cellData.F != nil {
  321. cellData.F.Content = formula
  322. } else {
  323. cellData.F = &xlsxF{Content: formula}
  324. }
  325. for _, o := range opts {
  326. if o.Type != nil {
  327. cellData.F.T = *o.Type
  328. }
  329. if o.Ref != nil {
  330. cellData.F.Ref = *o.Ref
  331. }
  332. }
  333. return err
  334. }
  335. // GetCellHyperLink provides a function to get cell hyperlink by given
  336. // worksheet name and axis. Boolean type value link will be ture if the cell
  337. // has a hyperlink and the target is the address of the hyperlink. Otherwise,
  338. // the value of link will be false and the value of the target will be a blank
  339. // string. For example get hyperlink of Sheet1!H6:
  340. //
  341. // link, target, err := f.GetCellHyperLink("Sheet1", "H6")
  342. //
  343. func (f *File) GetCellHyperLink(sheet, axis string) (bool, string, error) {
  344. // Check for correct cell name
  345. if _, _, err := SplitCellName(axis); err != nil {
  346. return false, "", err
  347. }
  348. xlsx, err := f.workSheetReader(sheet)
  349. if err != nil {
  350. return false, "", err
  351. }
  352. axis, err = f.mergeCellsParser(xlsx, axis)
  353. if err != nil {
  354. return false, "", err
  355. }
  356. if xlsx.Hyperlinks != nil {
  357. for _, link := range xlsx.Hyperlinks.Hyperlink {
  358. if link.Ref == axis {
  359. if link.RID != "" {
  360. return true, f.getSheetRelationshipsTargetByID(sheet, link.RID), err
  361. }
  362. return true, link.Location, err
  363. }
  364. }
  365. }
  366. return false, "", err
  367. }
  368. // SetCellHyperLink provides a function to set cell hyperlink by given
  369. // worksheet name and link URL address. LinkType defines two types of
  370. // hyperlink "External" for web site or "Location" for moving to one of cell
  371. // in this workbook. Maximum limit hyperlinks in a worksheet is 65530. The
  372. // below is example for external link.
  373. //
  374. // err := f.SetCellHyperLink("Sheet1", "A3", "https://github.com/360EntSecGroup-Skylar/excelize", "External")
  375. // // Set underline and font color style for the cell.
  376. // style, err := f.NewStyle(`{"font":{"color":"#1265BE","underline":"single"}}`)
  377. // err = f.SetCellStyle("Sheet1", "A3", "A3", style)
  378. //
  379. // A this is another example for "Location":
  380. //
  381. // err := f.SetCellHyperLink("Sheet1", "A3", "Sheet1!A40", "Location")
  382. //
  383. func (f *File) SetCellHyperLink(sheet, axis, link, linkType string) error {
  384. // Check for correct cell name
  385. if _, _, err := SplitCellName(axis); err != nil {
  386. return err
  387. }
  388. xlsx, err := f.workSheetReader(sheet)
  389. if err != nil {
  390. return err
  391. }
  392. axis, err = f.mergeCellsParser(xlsx, axis)
  393. if err != nil {
  394. return err
  395. }
  396. var linkData xlsxHyperlink
  397. if xlsx.Hyperlinks == nil {
  398. xlsx.Hyperlinks = new(xlsxHyperlinks)
  399. }
  400. if len(xlsx.Hyperlinks.Hyperlink) > 65529 {
  401. return errors.New("over maximum limit hyperlinks in a worksheet")
  402. }
  403. switch linkType {
  404. case "External":
  405. linkData = xlsxHyperlink{
  406. Ref: axis,
  407. }
  408. sheetPath := f.sheetMap[trimSheetName(sheet)]
  409. sheetRels := "xl/worksheets/_rels/" + strings.TrimPrefix(sheetPath, "xl/worksheets/") + ".rels"
  410. rID := f.addRels(sheetRels, SourceRelationshipHyperLink, link, linkType)
  411. linkData.RID = "rId" + strconv.Itoa(rID)
  412. case "Location":
  413. linkData = xlsxHyperlink{
  414. Ref: axis,
  415. Location: link,
  416. }
  417. default:
  418. return fmt.Errorf("invalid link type %q", linkType)
  419. }
  420. xlsx.Hyperlinks.Hyperlink = append(xlsx.Hyperlinks.Hyperlink, linkData)
  421. return nil
  422. }
  423. // SetCellRichText provides a function to set cell with rich text by given
  424. // worksheet. For example, set rich text on the A1 cell of the worksheet named
  425. // Sheet1:
  426. //
  427. // package main
  428. //
  429. // import (
  430. // "fmt"
  431. //
  432. // "github.com/360EntSecGroup-Skylar/excelize"
  433. // )
  434. //
  435. // func main() {
  436. // f := excelize.NewFile()
  437. // if err := f.SetRowHeight("Sheet1", 1, 35); err != nil {
  438. // fmt.Println(err)
  439. // return
  440. // }
  441. // if err := f.SetColWidth("Sheet1", "A", "A", 44); err != nil {
  442. // fmt.Println(err)
  443. // return
  444. // }
  445. // if err := f.SetCellRichText("Sheet1", "A1", []excelize.RichTextRun{
  446. // {
  447. // Text: "blod",
  448. // Font: &excelize.Font{
  449. // Bold: true,
  450. // Color: "2354e8",
  451. // Family: "Times New Roman",
  452. // },
  453. // },
  454. // {
  455. // Text: " and ",
  456. // Font: &excelize.Font{
  457. // Family: "Times New Roman",
  458. // },
  459. // },
  460. // {
  461. // Text: " italic",
  462. // Font: &excelize.Font{
  463. // Bold: true,
  464. // Color: "e83723",
  465. // Italic: true,
  466. // Family: "Times New Roman",
  467. // },
  468. // },
  469. // {
  470. // Text: "text with color and font-family,",
  471. // Font: &excelize.Font{
  472. // Bold: true,
  473. // Color: "2354e8",
  474. // Family: "Times New Roman",
  475. // },
  476. // },
  477. // {
  478. // Text: "\r\nlarge text with ",
  479. // Font: &excelize.Font{
  480. // Size: 14,
  481. // Color: "ad23e8",
  482. // },
  483. // },
  484. // {
  485. // Text: "strike",
  486. // Font: &excelize.Font{
  487. // Color: "e89923",
  488. // Strike: true,
  489. // },
  490. // },
  491. // {
  492. // Text: " and ",
  493. // Font: &excelize.Font{
  494. // Size: 14,
  495. // Color: "ad23e8",
  496. // },
  497. // },
  498. // {
  499. // Text: "underline.",
  500. // Font: &excelize.Font{
  501. // Color: "23e833",
  502. // Underline: "single",
  503. // },
  504. // },
  505. // }); err != nil {
  506. // fmt.Println(err)
  507. // return
  508. // }
  509. // style, err := f.NewStyle(&excelize.Style{
  510. // Alignment: &excelize.Alignment{
  511. // WrapText: true,
  512. // },
  513. // })
  514. // if err != nil {
  515. // fmt.Println(err)
  516. // return
  517. // }
  518. // if err := f.SetCellStyle("Sheet1", "A1", "A1", style); err != nil {
  519. // fmt.Println(err)
  520. // return
  521. // }
  522. // if err := f.SaveAs("Book1.xlsx"); err != nil {
  523. // fmt.Println(err)
  524. // }
  525. // }
  526. //
  527. func (f *File) SetCellRichText(sheet, cell string, runs []RichTextRun) error {
  528. ws, err := f.workSheetReader(sheet)
  529. if err != nil {
  530. return err
  531. }
  532. cellData, col, _, err := f.prepareCell(ws, sheet, cell)
  533. if err != nil {
  534. return err
  535. }
  536. cellData.S = f.prepareCellStyle(ws, col, cellData.S)
  537. si := xlsxSI{}
  538. sst := f.sharedStringsReader()
  539. textRuns := []xlsxR{}
  540. for _, textRun := range runs {
  541. run := xlsxR{T: &xlsxT{Val: textRun.Text}}
  542. if strings.ContainsAny(textRun.Text, "\r\n ") {
  543. run.T.Space = "preserve"
  544. }
  545. fnt := textRun.Font
  546. if fnt != nil {
  547. rpr := xlsxRPr{}
  548. if fnt.Bold {
  549. rpr.B = " "
  550. }
  551. if fnt.Italic {
  552. rpr.I = " "
  553. }
  554. if fnt.Strike {
  555. rpr.Strike = " "
  556. }
  557. if fnt.Underline != "" {
  558. rpr.U = &attrValString{Val: &fnt.Underline}
  559. }
  560. if fnt.Family != "" {
  561. rpr.RFont = &attrValString{Val: &fnt.Family}
  562. }
  563. if fnt.Size > 0.0 {
  564. rpr.Sz = &attrValFloat{Val: &fnt.Size}
  565. }
  566. if fnt.Color != "" {
  567. rpr.Color = &xlsxColor{RGB: getPaletteColor(fnt.Color)}
  568. }
  569. run.RPr = &rpr
  570. }
  571. textRuns = append(textRuns, run)
  572. }
  573. si.R = textRuns
  574. sst.SI = append(sst.SI, si)
  575. sst.Count++
  576. sst.UniqueCount++
  577. cellData.T, cellData.V = "s", strconv.Itoa(len(sst.SI)-1)
  578. f.addContentTypePart(0, "sharedStrings")
  579. rels := f.relsReader("xl/_rels/workbook.xml.rels")
  580. for _, rel := range rels.Relationships {
  581. if rel.Target == "sharedStrings.xml" {
  582. return err
  583. }
  584. }
  585. // Update xl/_rels/workbook.xml.rels
  586. f.addRels("xl/_rels/workbook.xml.rels", SourceRelationshipSharedStrings, "sharedStrings.xml", "")
  587. return err
  588. }
  589. // SetSheetRow writes an array to row by given worksheet name, starting
  590. // coordinate and a pointer to array type 'slice'. For example, writes an
  591. // array to row 6 start with the cell B6 on Sheet1:
  592. //
  593. // err := f.SetSheetRow("Sheet1", "B6", &[]interface{}{"1", nil, 2})
  594. //
  595. func (f *File) SetSheetRow(sheet, axis string, slice interface{}) error {
  596. col, row, err := CellNameToCoordinates(axis)
  597. if err != nil {
  598. return err
  599. }
  600. // Make sure 'slice' is a Ptr to Slice
  601. v := reflect.ValueOf(slice)
  602. if v.Kind() != reflect.Ptr || v.Elem().Kind() != reflect.Slice {
  603. return errors.New("pointer to slice expected")
  604. }
  605. v = v.Elem()
  606. for i := 0; i < v.Len(); i++ {
  607. cell, err := CoordinatesToCellName(col+i, row)
  608. // Error should never happens here. But keep checking to early detect regresions
  609. // if it will be introduced in future.
  610. if err != nil {
  611. return err
  612. }
  613. if err := f.SetCellValue(sheet, cell, v.Index(i).Interface()); err != nil {
  614. return err
  615. }
  616. }
  617. return err
  618. }
  619. // getCellInfo does common preparation for all SetCell* methods.
  620. func (f *File) prepareCell(xlsx *xlsxWorksheet, sheet, cell string) (*xlsxC, int, int, error) {
  621. var err error
  622. cell, err = f.mergeCellsParser(xlsx, cell)
  623. if err != nil {
  624. return nil, 0, 0, err
  625. }
  626. col, row, err := CellNameToCoordinates(cell)
  627. if err != nil {
  628. return nil, 0, 0, err
  629. }
  630. prepareSheetXML(xlsx, col, row)
  631. return &xlsx.SheetData.Row[row-1].C[col-1], col, row, err
  632. }
  633. // getCellStringFunc does common value extraction workflow for all GetCell*
  634. // methods. Passed function implements specific part of required logic.
  635. func (f *File) getCellStringFunc(sheet, axis string, fn func(x *xlsxWorksheet, c *xlsxC) (string, bool, error)) (string, error) {
  636. xlsx, err := f.workSheetReader(sheet)
  637. if err != nil {
  638. return "", err
  639. }
  640. axis, err = f.mergeCellsParser(xlsx, axis)
  641. if err != nil {
  642. return "", err
  643. }
  644. _, row, err := CellNameToCoordinates(axis)
  645. if err != nil {
  646. return "", err
  647. }
  648. lastRowNum := 0
  649. if l := len(xlsx.SheetData.Row); l > 0 {
  650. lastRowNum = xlsx.SheetData.Row[l-1].R
  651. }
  652. // keep in mind: row starts from 1
  653. if row > lastRowNum {
  654. return "", nil
  655. }
  656. for rowIdx := range xlsx.SheetData.Row {
  657. rowData := &xlsx.SheetData.Row[rowIdx]
  658. if rowData.R != row {
  659. continue
  660. }
  661. for colIdx := range rowData.C {
  662. colData := &rowData.C[colIdx]
  663. if axis != colData.R {
  664. continue
  665. }
  666. val, ok, err := fn(xlsx, colData)
  667. if err != nil {
  668. return "", err
  669. }
  670. if ok {
  671. return val, nil
  672. }
  673. }
  674. }
  675. return "", nil
  676. }
  677. // formattedValue provides a function to returns a value after formatted. If
  678. // it is possible to apply a format to the cell value, it will do so, if not
  679. // then an error will be returned, along with the raw value of the cell.
  680. func (f *File) formattedValue(s int, v string) string {
  681. if s == 0 {
  682. return v
  683. }
  684. styleSheet := f.stylesReader()
  685. ok := builtInNumFmtFunc[styleSheet.CellXfs.Xf[s].NumFmtID]
  686. if ok != nil {
  687. return ok(styleSheet.CellXfs.Xf[s].NumFmtID, v)
  688. }
  689. return v
  690. }
  691. // prepareCellStyle provides a function to prepare style index of cell in
  692. // worksheet by given column index and style index.
  693. func (f *File) prepareCellStyle(xlsx *xlsxWorksheet, col, style int) int {
  694. if xlsx.Cols != nil && style == 0 {
  695. for _, c := range xlsx.Cols.Col {
  696. if c.Min <= col && col <= c.Max {
  697. style = c.Style
  698. }
  699. }
  700. }
  701. return style
  702. }
  703. // mergeCellsParser provides a function to check merged cells in worksheet by
  704. // given axis.
  705. func (f *File) mergeCellsParser(xlsx *xlsxWorksheet, axis string) (string, error) {
  706. axis = strings.ToUpper(axis)
  707. if xlsx.MergeCells != nil {
  708. for i := 0; i < len(xlsx.MergeCells.Cells); i++ {
  709. ok, err := f.checkCellInArea(axis, xlsx.MergeCells.Cells[i].Ref)
  710. if err != nil {
  711. return axis, err
  712. }
  713. if ok {
  714. axis = strings.Split(xlsx.MergeCells.Cells[i].Ref, ":")[0]
  715. }
  716. }
  717. }
  718. return axis, nil
  719. }
  720. // checkCellInArea provides a function to determine if a given coordinate is
  721. // within an area.
  722. func (f *File) checkCellInArea(cell, area string) (bool, error) {
  723. col, row, err := CellNameToCoordinates(cell)
  724. if err != nil {
  725. return false, err
  726. }
  727. rng := strings.Split(area, ":")
  728. if len(rng) != 2 {
  729. return false, err
  730. }
  731. coordinates, err := f.areaRefToCoordinates(area)
  732. if err != nil {
  733. return false, err
  734. }
  735. return cellInRef([]int{col, row}, coordinates), err
  736. }
  737. // cellInRef provides a function to determine if a given range is within an
  738. // range.
  739. func cellInRef(cell, ref []int) bool {
  740. return cell[0] >= ref[0] && cell[0] <= ref[2] && cell[1] >= ref[1] && cell[1] <= ref[3]
  741. }
  742. // isOverlap find if the given two rectangles overlap or not.
  743. func isOverlap(rect1, rect2 []int) bool {
  744. return cellInRef([]int{rect1[0], rect1[1]}, rect2) ||
  745. cellInRef([]int{rect1[2], rect1[1]}, rect2) ||
  746. cellInRef([]int{rect1[0], rect1[3]}, rect2) ||
  747. cellInRef([]int{rect1[2], rect1[3]}, rect2) ||
  748. cellInRef([]int{rect2[0], rect2[1]}, rect1) ||
  749. cellInRef([]int{rect2[2], rect2[1]}, rect1) ||
  750. cellInRef([]int{rect2[0], rect2[3]}, rect1) ||
  751. cellInRef([]int{rect2[2], rect2[3]}, rect1)
  752. }
  753. // getSharedForumula find a cell contains the same formula as another cell,
  754. // the "shared" value can be used for the t attribute and the si attribute can
  755. // be used to refer to the cell containing the formula. Two formulas are
  756. // considered to be the same when their respective representations in
  757. // R1C1-reference notation, are the same.
  758. //
  759. // Note that this function not validate ref tag to check the cell if or not in
  760. // allow area, and always return origin shared formula.
  761. func getSharedForumula(xlsx *xlsxWorksheet, si string) string {
  762. for _, r := range xlsx.SheetData.Row {
  763. for _, c := range r.C {
  764. if c.F != nil && c.F.Ref != "" && c.F.T == STCellFormulaTypeShared && c.F.Si == si {
  765. return c.F.Content
  766. }
  767. }
  768. }
  769. return ""
  770. }