cell.go 24 KB

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