cell.go 23 KB

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