cell.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864
  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 / XLSM / XLTM files. Supports reading and writing
  7. // spreadsheet documents generated by Microsoft Exce™ 2007 and later. Supports
  8. // complex components by high compatibility, and provided streaming API for
  9. // generating or reading data from a worksheet with huge amounts of data. This
  10. // library needs Go version 1.10 or later.
  11. package excelize
  12. import (
  13. "encoding/xml"
  14. "errors"
  15. "fmt"
  16. "reflect"
  17. "strconv"
  18. "strings"
  19. "sync"
  20. "time"
  21. )
  22. const (
  23. // STCellFormulaTypeArray defined the formula is an array formula.
  24. STCellFormulaTypeArray = "array"
  25. // STCellFormulaTypeDataTable defined the formula is a data table formula.
  26. STCellFormulaTypeDataTable = "dataTable"
  27. // STCellFormulaTypeNormal defined the formula is a regular cell formula.
  28. STCellFormulaTypeNormal = "normal"
  29. // STCellFormulaTypeShared defined the formula is part of a shared formula.
  30. STCellFormulaTypeShared = "shared"
  31. )
  32. var rwMutex sync.RWMutex
  33. // GetCellValue provides a function to get formatted value from cell by given
  34. // worksheet name and axis in XLSX file. If it is possible to apply a format
  35. // to the cell value, it will do so, if not then an error will be returned,
  36. // along with the raw value of the cell.
  37. func (f *File) GetCellValue(sheet, axis string) (string, error) {
  38. return f.getCellStringFunc(sheet, axis, func(x *xlsxWorksheet, c *xlsxC) (string, bool, error) {
  39. val, err := c.getValueFrom(f, f.sharedStringsReader())
  40. return val, true, err
  41. })
  42. }
  43. // SetCellValue provides a function to set value of a cell. The specified
  44. // coordinates should not be in the first row of the table. The following
  45. // shows the supported data types:
  46. //
  47. // int
  48. // int8
  49. // int16
  50. // int32
  51. // int64
  52. // uint
  53. // uint8
  54. // uint16
  55. // uint32
  56. // uint64
  57. // float32
  58. // float64
  59. // string
  60. // []byte
  61. // time.Duration
  62. // time.Time
  63. // bool
  64. // nil
  65. //
  66. // Note that default date format is m/d/yy h:mm of time.Time type value. You can
  67. // set numbers format by SetCellStyle() method.
  68. func (f *File) SetCellValue(sheet, axis string, value interface{}) error {
  69. var err error
  70. switch v := value.(type) {
  71. case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
  72. err = f.setCellIntFunc(sheet, axis, v)
  73. case float32:
  74. err = f.SetCellFloat(sheet, axis, float64(v), -1, 32)
  75. case float64:
  76. err = f.SetCellFloat(sheet, axis, v, -1, 64)
  77. case string:
  78. err = f.SetCellStr(sheet, axis, v)
  79. case []byte:
  80. err = f.SetCellStr(sheet, axis, string(v))
  81. case time.Duration:
  82. _, d := setCellDuration(v)
  83. err = f.SetCellDefault(sheet, axis, d)
  84. if err != nil {
  85. return err
  86. }
  87. err = f.setDefaultTimeStyle(sheet, axis, 21)
  88. case time.Time:
  89. err = f.setCellTimeFunc(sheet, axis, v)
  90. case bool:
  91. err = f.SetCellBool(sheet, axis, v)
  92. case nil:
  93. err = f.SetCellStr(sheet, axis, "")
  94. default:
  95. err = f.SetCellStr(sheet, axis, fmt.Sprint(value))
  96. }
  97. return err
  98. }
  99. // setCellIntFunc is a wrapper of SetCellInt.
  100. func (f *File) setCellIntFunc(sheet, axis string, value interface{}) error {
  101. var err error
  102. switch v := value.(type) {
  103. case int:
  104. err = f.SetCellInt(sheet, axis, v)
  105. case int8:
  106. err = f.SetCellInt(sheet, axis, int(v))
  107. case int16:
  108. err = f.SetCellInt(sheet, axis, int(v))
  109. case int32:
  110. err = f.SetCellInt(sheet, axis, int(v))
  111. case int64:
  112. err = f.SetCellInt(sheet, axis, int(v))
  113. case uint:
  114. err = f.SetCellInt(sheet, axis, int(v))
  115. case uint8:
  116. err = f.SetCellInt(sheet, axis, int(v))
  117. case uint16:
  118. err = f.SetCellInt(sheet, axis, int(v))
  119. case uint32:
  120. err = f.SetCellInt(sheet, axis, int(v))
  121. case uint64:
  122. err = f.SetCellInt(sheet, axis, int(v))
  123. }
  124. return err
  125. }
  126. // setCellTimeFunc provides a method to process time type of value for
  127. // SetCellValue.
  128. func (f *File) setCellTimeFunc(sheet, axis string, value time.Time) error {
  129. xlsx, err := f.workSheetReader(sheet)
  130. if err != nil {
  131. return err
  132. }
  133. cellData, col, _, err := f.prepareCell(xlsx, sheet, axis)
  134. if err != nil {
  135. return err
  136. }
  137. cellData.S = f.prepareCellStyle(xlsx, col, cellData.S)
  138. var isNum bool
  139. cellData.T, cellData.V, isNum, err = setCellTime(value)
  140. if err != nil {
  141. return err
  142. }
  143. if isNum {
  144. err = f.setDefaultTimeStyle(sheet, axis, 22)
  145. if err != nil {
  146. return err
  147. }
  148. }
  149. return err
  150. }
  151. func setCellTime(value time.Time) (t string, b string, isNum bool, err error) {
  152. var excelTime float64
  153. excelTime, err = timeToExcelTime(value)
  154. if err != nil {
  155. return
  156. }
  157. isNum = excelTime > 0
  158. if isNum {
  159. t, b = setCellDefault(strconv.FormatFloat(excelTime, 'f', -1, 64))
  160. } else {
  161. t, b = setCellDefault(value.Format(time.RFC3339Nano))
  162. }
  163. return
  164. }
  165. func setCellDuration(value time.Duration) (t string, v string) {
  166. v = strconv.FormatFloat(value.Seconds()/86400.0, 'f', -1, 32)
  167. return
  168. }
  169. // SetCellInt provides a function to set int type value of a cell by given
  170. // worksheet name, cell coordinates and cell value.
  171. func (f *File) SetCellInt(sheet, axis string, value int) error {
  172. rwMutex.Lock()
  173. defer rwMutex.Unlock()
  174. xlsx, err := f.workSheetReader(sheet)
  175. if err != nil {
  176. return err
  177. }
  178. cellData, col, _, err := f.prepareCell(xlsx, sheet, axis)
  179. if err != nil {
  180. return err
  181. }
  182. cellData.S = f.prepareCellStyle(xlsx, col, cellData.S)
  183. cellData.T, cellData.V = setCellInt(value)
  184. return err
  185. }
  186. func setCellInt(value int) (t string, v string) {
  187. v = strconv.Itoa(value)
  188. return
  189. }
  190. // SetCellBool provides a function to set bool type value of a cell by given
  191. // worksheet name, cell name and cell value.
  192. func (f *File) SetCellBool(sheet, axis string, value bool) error {
  193. rwMutex.Lock()
  194. defer rwMutex.Unlock()
  195. xlsx, err := f.workSheetReader(sheet)
  196. if err != nil {
  197. return err
  198. }
  199. cellData, col, _, err := f.prepareCell(xlsx, sheet, axis)
  200. if err != nil {
  201. return err
  202. }
  203. cellData.S = f.prepareCellStyle(xlsx, col, cellData.S)
  204. cellData.T, cellData.V = setCellBool(value)
  205. return err
  206. }
  207. func setCellBool(value bool) (t string, v string) {
  208. t = "b"
  209. if value {
  210. v = "1"
  211. } else {
  212. v = "0"
  213. }
  214. return
  215. }
  216. // SetCellFloat sets a floating point value into a cell. The prec parameter
  217. // specifies how many places after the decimal will be shown while -1 is a
  218. // special value that will use as many decimal places as necessary to
  219. // represent the number. bitSize is 32 or 64 depending on if a float32 or
  220. // float64 was originally used for the value. For Example:
  221. //
  222. // var x float32 = 1.325
  223. // f.SetCellFloat("Sheet1", "A1", float64(x), 2, 32)
  224. //
  225. func (f *File) SetCellFloat(sheet, axis string, value float64, prec, bitSize int) error {
  226. rwMutex.Lock()
  227. defer rwMutex.Unlock()
  228. xlsx, err := f.workSheetReader(sheet)
  229. if err != nil {
  230. return err
  231. }
  232. cellData, col, _, err := f.prepareCell(xlsx, sheet, axis)
  233. if err != nil {
  234. return err
  235. }
  236. cellData.S = f.prepareCellStyle(xlsx, col, cellData.S)
  237. cellData.T, cellData.V = setCellFloat(value, prec, bitSize)
  238. return err
  239. }
  240. func setCellFloat(value float64, prec, bitSize int) (t string, v string) {
  241. v = strconv.FormatFloat(value, 'f', prec, bitSize)
  242. return
  243. }
  244. // SetCellStr provides a function to set string type value of a cell. Total
  245. // number of characters that a cell can contain 32767 characters.
  246. func (f *File) SetCellStr(sheet, axis, value string) error {
  247. rwMutex.Lock()
  248. defer rwMutex.Unlock()
  249. xlsx, err := f.workSheetReader(sheet)
  250. if err != nil {
  251. return err
  252. }
  253. cellData, col, _, err := f.prepareCell(xlsx, sheet, axis)
  254. if err != nil {
  255. return err
  256. }
  257. cellData.S = f.prepareCellStyle(xlsx, col, cellData.S)
  258. cellData.T, cellData.V = f.setCellString(value)
  259. return err
  260. }
  261. // setCellString provides a function to set string type to shared string
  262. // table.
  263. func (f *File) setCellString(value string) (t string, v string) {
  264. if len(value) > TotalCellChars {
  265. value = value[0:TotalCellChars]
  266. }
  267. t = "s"
  268. v = strconv.Itoa(f.setSharedString(value))
  269. return
  270. }
  271. // setSharedString provides a function to add string to the share string table.
  272. func (f *File) setSharedString(val string) int {
  273. sst := f.sharedStringsReader()
  274. if i, ok := f.sharedStringsMap[val]; ok {
  275. return i
  276. }
  277. sst.Count++
  278. sst.UniqueCount++
  279. t := xlsxT{Val: val}
  280. // Leading and ending space(s) character detection.
  281. if len(val) > 0 && (val[0] == 32 || val[len(val)-1] == 32) {
  282. ns := xml.Attr{
  283. Name: xml.Name{Space: NameSpaceXML, Local: "space"},
  284. Value: "preserve",
  285. }
  286. t.Space = ns
  287. }
  288. sst.SI = append(sst.SI, xlsxSI{T: &t})
  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. f.addSheetNameSpace(sheet, SourceRelationship)
  456. case "Location":
  457. linkData = xlsxHyperlink{
  458. Ref: axis,
  459. Location: link,
  460. }
  461. default:
  462. return fmt.Errorf("invalid link type %q", linkType)
  463. }
  464. xlsx.Hyperlinks.Hyperlink = append(xlsx.Hyperlinks.Hyperlink, linkData)
  465. return nil
  466. }
  467. // SetCellRichText provides a function to set cell with rich text by given
  468. // worksheet. For example, set rich text on the A1 cell of the worksheet named
  469. // Sheet1:
  470. //
  471. // package main
  472. //
  473. // import (
  474. // "fmt"
  475. //
  476. // "github.com/360EntSecGroup-Skylar/excelize"
  477. // )
  478. //
  479. // func main() {
  480. // f := excelize.NewFile()
  481. // if err := f.SetRowHeight("Sheet1", 1, 35); err != nil {
  482. // fmt.Println(err)
  483. // return
  484. // }
  485. // if err := f.SetColWidth("Sheet1", "A", "A", 44); err != nil {
  486. // fmt.Println(err)
  487. // return
  488. // }
  489. // if err := f.SetCellRichText("Sheet1", "A1", []excelize.RichTextRun{
  490. // {
  491. // Text: "blod",
  492. // Font: &excelize.Font{
  493. // Bold: true,
  494. // Color: "2354e8",
  495. // Family: "Times New Roman",
  496. // },
  497. // },
  498. // {
  499. // Text: " and ",
  500. // Font: &excelize.Font{
  501. // Family: "Times New Roman",
  502. // },
  503. // },
  504. // {
  505. // Text: " italic",
  506. // Font: &excelize.Font{
  507. // Bold: true,
  508. // Color: "e83723",
  509. // Italic: true,
  510. // Family: "Times New Roman",
  511. // },
  512. // },
  513. // {
  514. // Text: "text with color and font-family,",
  515. // Font: &excelize.Font{
  516. // Bold: true,
  517. // Color: "2354e8",
  518. // Family: "Times New Roman",
  519. // },
  520. // },
  521. // {
  522. // Text: "\r\nlarge text with ",
  523. // Font: &excelize.Font{
  524. // Size: 14,
  525. // Color: "ad23e8",
  526. // },
  527. // },
  528. // {
  529. // Text: "strike",
  530. // Font: &excelize.Font{
  531. // Color: "e89923",
  532. // Strike: true,
  533. // },
  534. // },
  535. // {
  536. // Text: " and ",
  537. // Font: &excelize.Font{
  538. // Size: 14,
  539. // Color: "ad23e8",
  540. // },
  541. // },
  542. // {
  543. // Text: "underline.",
  544. // Font: &excelize.Font{
  545. // Color: "23e833",
  546. // Underline: "single",
  547. // },
  548. // },
  549. // }); err != nil {
  550. // fmt.Println(err)
  551. // return
  552. // }
  553. // style, err := f.NewStyle(&excelize.Style{
  554. // Alignment: &excelize.Alignment{
  555. // WrapText: true,
  556. // },
  557. // })
  558. // if err != nil {
  559. // fmt.Println(err)
  560. // return
  561. // }
  562. // if err := f.SetCellStyle("Sheet1", "A1", "A1", style); err != nil {
  563. // fmt.Println(err)
  564. // return
  565. // }
  566. // if err := f.SaveAs("Book1.xlsx"); err != nil {
  567. // fmt.Println(err)
  568. // }
  569. // }
  570. //
  571. func (f *File) SetCellRichText(sheet, cell string, runs []RichTextRun) error {
  572. ws, err := f.workSheetReader(sheet)
  573. if err != nil {
  574. return err
  575. }
  576. cellData, col, _, err := f.prepareCell(ws, sheet, cell)
  577. if err != nil {
  578. return err
  579. }
  580. cellData.S = f.prepareCellStyle(ws, col, cellData.S)
  581. si := xlsxSI{}
  582. sst := f.sharedStringsReader()
  583. textRuns := []xlsxR{}
  584. for _, textRun := range runs {
  585. run := xlsxR{T: &xlsxT{Val: textRun.Text}}
  586. if strings.ContainsAny(textRun.Text, "\r\n ") {
  587. run.T.Space = xml.Attr{Name: xml.Name{Space: NameSpaceXML, Local: "space"}, Value: "preserve"}
  588. }
  589. fnt := textRun.Font
  590. if fnt != nil {
  591. rpr := xlsxRPr{}
  592. if fnt.Bold {
  593. rpr.B = " "
  594. }
  595. if fnt.Italic {
  596. rpr.I = " "
  597. }
  598. if fnt.Strike {
  599. rpr.Strike = " "
  600. }
  601. if fnt.Underline != "" {
  602. rpr.U = &attrValString{Val: &fnt.Underline}
  603. }
  604. if fnt.Family != "" {
  605. rpr.RFont = &attrValString{Val: &fnt.Family}
  606. }
  607. if fnt.Size > 0.0 {
  608. rpr.Sz = &attrValFloat{Val: &fnt.Size}
  609. }
  610. if fnt.Color != "" {
  611. rpr.Color = &xlsxColor{RGB: getPaletteColor(fnt.Color)}
  612. }
  613. run.RPr = &rpr
  614. }
  615. textRuns = append(textRuns, run)
  616. }
  617. si.R = textRuns
  618. sst.SI = append(sst.SI, si)
  619. sst.Count++
  620. sst.UniqueCount++
  621. cellData.T, cellData.V = "s", strconv.Itoa(len(sst.SI)-1)
  622. return err
  623. }
  624. // SetSheetRow writes an array to row by given worksheet name, starting
  625. // coordinate and a pointer to array type 'slice'. For example, writes an
  626. // array to row 6 start with the cell B6 on Sheet1:
  627. //
  628. // err := f.SetSheetRow("Sheet1", "B6", &[]interface{}{"1", nil, 2})
  629. //
  630. func (f *File) SetSheetRow(sheet, axis string, slice interface{}) error {
  631. col, row, err := CellNameToCoordinates(axis)
  632. if err != nil {
  633. return err
  634. }
  635. // Make sure 'slice' is a Ptr to Slice
  636. v := reflect.ValueOf(slice)
  637. if v.Kind() != reflect.Ptr || v.Elem().Kind() != reflect.Slice {
  638. return errors.New("pointer to slice expected")
  639. }
  640. v = v.Elem()
  641. for i := 0; i < v.Len(); i++ {
  642. cell, err := CoordinatesToCellName(col+i, row)
  643. // Error should never happens here. But keep checking to early detect regresions
  644. // if it will be introduced in future.
  645. if err != nil {
  646. return err
  647. }
  648. if err := f.SetCellValue(sheet, cell, v.Index(i).Interface()); err != nil {
  649. return err
  650. }
  651. }
  652. return err
  653. }
  654. // getCellInfo does common preparation for all SetCell* methods.
  655. func (f *File) prepareCell(xlsx *xlsxWorksheet, sheet, cell string) (*xlsxC, int, int, error) {
  656. var err error
  657. cell, err = f.mergeCellsParser(xlsx, cell)
  658. if err != nil {
  659. return nil, 0, 0, err
  660. }
  661. col, row, err := CellNameToCoordinates(cell)
  662. if err != nil {
  663. return nil, 0, 0, err
  664. }
  665. prepareSheetXML(xlsx, col, row)
  666. return &xlsx.SheetData.Row[row-1].C[col-1], col, row, err
  667. }
  668. // getCellStringFunc does common value extraction workflow for all GetCell*
  669. // methods. Passed function implements specific part of required logic.
  670. func (f *File) getCellStringFunc(sheet, axis string, fn func(x *xlsxWorksheet, c *xlsxC) (string, bool, error)) (string, error) {
  671. xlsx, err := f.workSheetReader(sheet)
  672. if err != nil {
  673. return "", err
  674. }
  675. axis, err = f.mergeCellsParser(xlsx, axis)
  676. if err != nil {
  677. return "", err
  678. }
  679. _, row, err := CellNameToCoordinates(axis)
  680. if err != nil {
  681. return "", err
  682. }
  683. lastRowNum := 0
  684. if l := len(xlsx.SheetData.Row); l > 0 {
  685. lastRowNum = xlsx.SheetData.Row[l-1].R
  686. }
  687. // keep in mind: row starts from 1
  688. if row > lastRowNum {
  689. return "", nil
  690. }
  691. for rowIdx := range xlsx.SheetData.Row {
  692. rowData := &xlsx.SheetData.Row[rowIdx]
  693. if rowData.R != row {
  694. continue
  695. }
  696. for colIdx := range rowData.C {
  697. colData := &rowData.C[colIdx]
  698. if axis != colData.R {
  699. continue
  700. }
  701. val, ok, err := fn(xlsx, colData)
  702. if err != nil {
  703. return "", err
  704. }
  705. if ok {
  706. return val, nil
  707. }
  708. }
  709. }
  710. return "", nil
  711. }
  712. // formattedValue provides a function to returns a value after formatted. If
  713. // it is possible to apply a format to the cell value, it will do so, if not
  714. // then an error will be returned, along with the raw value of the cell.
  715. func (f *File) formattedValue(s int, v string) string {
  716. if s == 0 {
  717. return v
  718. }
  719. styleSheet := f.stylesReader()
  720. ok := builtInNumFmtFunc[*styleSheet.CellXfs.Xf[s].NumFmtID]
  721. if ok != nil {
  722. return ok(*styleSheet.CellXfs.Xf[s].NumFmtID, v)
  723. }
  724. return v
  725. }
  726. // prepareCellStyle provides a function to prepare style index of cell in
  727. // worksheet by given column index and style index.
  728. func (f *File) prepareCellStyle(xlsx *xlsxWorksheet, col, style int) int {
  729. if xlsx.Cols != nil && style == 0 {
  730. for _, c := range xlsx.Cols.Col {
  731. if c.Min <= col && col <= c.Max {
  732. style = c.Style
  733. }
  734. }
  735. }
  736. return style
  737. }
  738. // mergeCellsParser provides a function to check merged cells in worksheet by
  739. // given axis.
  740. func (f *File) mergeCellsParser(xlsx *xlsxWorksheet, axis string) (string, error) {
  741. axis = strings.ToUpper(axis)
  742. if xlsx.MergeCells != nil {
  743. for i := 0; i < len(xlsx.MergeCells.Cells); i++ {
  744. ok, err := f.checkCellInArea(axis, xlsx.MergeCells.Cells[i].Ref)
  745. if err != nil {
  746. return axis, err
  747. }
  748. if ok {
  749. axis = strings.Split(xlsx.MergeCells.Cells[i].Ref, ":")[0]
  750. }
  751. }
  752. }
  753. return axis, nil
  754. }
  755. // checkCellInArea provides a function to determine if a given coordinate is
  756. // within an area.
  757. func (f *File) checkCellInArea(cell, area string) (bool, error) {
  758. col, row, err := CellNameToCoordinates(cell)
  759. if err != nil {
  760. return false, err
  761. }
  762. rng := strings.Split(area, ":")
  763. if len(rng) != 2 {
  764. return false, err
  765. }
  766. coordinates, err := f.areaRefToCoordinates(area)
  767. if err != nil {
  768. return false, err
  769. }
  770. return cellInRef([]int{col, row}, coordinates), err
  771. }
  772. // cellInRef provides a function to determine if a given range is within an
  773. // range.
  774. func cellInRef(cell, ref []int) bool {
  775. return cell[0] >= ref[0] && cell[0] <= ref[2] && cell[1] >= ref[1] && cell[1] <= ref[3]
  776. }
  777. // isOverlap find if the given two rectangles overlap or not.
  778. func isOverlap(rect1, rect2 []int) bool {
  779. return cellInRef([]int{rect1[0], rect1[1]}, rect2) ||
  780. cellInRef([]int{rect1[2], rect1[1]}, rect2) ||
  781. cellInRef([]int{rect1[0], rect1[3]}, rect2) ||
  782. cellInRef([]int{rect1[2], rect1[3]}, rect2) ||
  783. cellInRef([]int{rect2[0], rect2[1]}, rect1) ||
  784. cellInRef([]int{rect2[2], rect2[1]}, rect1) ||
  785. cellInRef([]int{rect2[0], rect2[3]}, rect1) ||
  786. cellInRef([]int{rect2[2], rect2[3]}, rect1)
  787. }
  788. // getSharedForumula find a cell contains the same formula as another cell,
  789. // the "shared" value can be used for the t attribute and the si attribute can
  790. // be used to refer to the cell containing the formula. Two formulas are
  791. // considered to be the same when their respective representations in
  792. // R1C1-reference notation, are the same.
  793. //
  794. // Note that this function not validate ref tag to check the cell if or not in
  795. // allow area, and always return origin shared formula.
  796. func getSharedForumula(xlsx *xlsxWorksheet, si string) string {
  797. for _, r := range xlsx.SheetData.Row {
  798. for _, c := range r.C {
  799. if c.F != nil && c.F.Ref != "" && c.F.T == STCellFormulaTypeShared && c.F.Si == si {
  800. return c.F.Content
  801. }
  802. }
  803. }
  804. return ""
  805. }