cell.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954
  1. // Copyright 2016 - 2021 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 Excel™ 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.15 or later.
  11. package excelize
  12. import (
  13. "encoding/xml"
  14. "errors"
  15. "fmt"
  16. "reflect"
  17. "strconv"
  18. "strings"
  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. // GetCellValue provides a function to get formatted value from cell by given
  32. // worksheet name and axis in spreadsheet file. If it is possible to apply a
  33. // format to the cell value, it will do so, if not then an error will be
  34. // returned, 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. return val, true, err
  39. })
  40. }
  41. // SetCellValue provides a function to set the value of a cell. The specified
  42. // coordinates should not be in the first row of the table, a complex number
  43. // can be set with string text. The following shows the supported data
  44. // 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.SetCellDefault(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. ws, err := f.workSheetReader(sheet)
  129. if err != nil {
  130. return err
  131. }
  132. cellData, col, _, err := f.prepareCell(ws, sheet, axis)
  133. if err != nil {
  134. return err
  135. }
  136. cellData.S = f.prepareCellStyle(ws, 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. ws, err := f.workSheetReader(sheet)
  172. if err != nil {
  173. return err
  174. }
  175. cellData, col, _, err := f.prepareCell(ws, sheet, axis)
  176. if err != nil {
  177. return err
  178. }
  179. cellData.S = f.prepareCellStyle(ws, 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. ws, err := f.workSheetReader(sheet)
  191. if err != nil {
  192. return err
  193. }
  194. cellData, col, _, err := f.prepareCell(ws, sheet, axis)
  195. if err != nil {
  196. return err
  197. }
  198. cellData.S = f.prepareCellStyle(ws, 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. ws, err := f.workSheetReader(sheet)
  222. if err != nil {
  223. return err
  224. }
  225. cellData, col, _, err := f.prepareCell(ws, sheet, axis)
  226. if err != nil {
  227. return err
  228. }
  229. cellData.S = f.prepareCellStyle(ws, 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. ws, err := f.workSheetReader(sheet)
  241. if err != nil {
  242. return err
  243. }
  244. cellData, col, _, err := f.prepareCell(ws, sheet, axis)
  245. if err != nil {
  246. return err
  247. }
  248. cellData.S = f.prepareCellStyle(ws, col, cellData.S)
  249. cellData.T, cellData.V = f.setCellString(value)
  250. return err
  251. }
  252. // setCellString provides a function to set string type to shared string
  253. // table.
  254. func (f *File) setCellString(value string) (t string, v string) {
  255. if len(value) > TotalCellChars {
  256. value = value[0:TotalCellChars]
  257. }
  258. t = "s"
  259. v = strconv.Itoa(f.setSharedString(value))
  260. return
  261. }
  262. // setSharedString provides a function to add string to the share string table.
  263. func (f *File) setSharedString(val string) int {
  264. sst := f.sharedStringsReader()
  265. f.Lock()
  266. defer f.Unlock()
  267. if i, ok := f.sharedStringsMap[val]; ok {
  268. return i
  269. }
  270. sst.Count++
  271. sst.UniqueCount++
  272. t := xlsxT{Val: val}
  273. // Leading and ending space(s) character detection.
  274. if len(val) > 0 && (val[0] == 32 || val[len(val)-1] == 32) {
  275. ns := xml.Attr{
  276. Name: xml.Name{Space: NameSpaceXML, Local: "space"},
  277. Value: "preserve",
  278. }
  279. t.Space = ns
  280. }
  281. sst.SI = append(sst.SI, xlsxSI{T: &t})
  282. f.sharedStringsMap[val] = sst.UniqueCount - 1
  283. return sst.UniqueCount - 1
  284. }
  285. // setCellStr provides a function to set string type to cell.
  286. func setCellStr(value string) (t string, v string, ns xml.Attr) {
  287. if len(value) > TotalCellChars {
  288. value = value[0:TotalCellChars]
  289. }
  290. // Leading and ending space(s) character detection.
  291. if len(value) > 0 && (value[0] == 32 || value[len(value)-1] == 32) {
  292. ns = xml.Attr{
  293. Name: xml.Name{Space: NameSpaceXML, Local: "space"},
  294. Value: "preserve",
  295. }
  296. }
  297. t = "str"
  298. v = value
  299. return
  300. }
  301. // SetCellDefault provides a function to set string type value of a cell as
  302. // default format without escaping the cell.
  303. func (f *File) SetCellDefault(sheet, axis, value string) error {
  304. ws, err := f.workSheetReader(sheet)
  305. if err != nil {
  306. return err
  307. }
  308. cellData, col, _, err := f.prepareCell(ws, sheet, axis)
  309. if err != nil {
  310. return err
  311. }
  312. cellData.S = f.prepareCellStyle(ws, col, cellData.S)
  313. cellData.T, cellData.V = setCellDefault(value)
  314. return err
  315. }
  316. func setCellDefault(value string) (t string, v string) {
  317. v = value
  318. return
  319. }
  320. // GetCellFormula provides a function to get formula from cell by given
  321. // worksheet name and axis in XLSX file.
  322. func (f *File) GetCellFormula(sheet, axis string) (string, error) {
  323. return f.getCellStringFunc(sheet, axis, func(x *xlsxWorksheet, c *xlsxC) (string, bool, error) {
  324. if c.F == nil {
  325. return "", false, nil
  326. }
  327. if c.F.T == STCellFormulaTypeShared {
  328. return getSharedForumula(x, c.F.Si), true, nil
  329. }
  330. return c.F.Content, true, nil
  331. })
  332. }
  333. // FormulaOpts can be passed to SetCellFormula to use other formula types.
  334. type FormulaOpts struct {
  335. Type *string // Formula type
  336. Ref *string // Shared formula ref
  337. }
  338. // SetCellFormula provides a function to set cell formula by given string and
  339. // worksheet name.
  340. func (f *File) SetCellFormula(sheet, axis, formula string, opts ...FormulaOpts) error {
  341. ws, err := f.workSheetReader(sheet)
  342. if err != nil {
  343. return err
  344. }
  345. cellData, _, _, err := f.prepareCell(ws, sheet, axis)
  346. if err != nil {
  347. return err
  348. }
  349. if formula == "" {
  350. cellData.F = nil
  351. f.deleteCalcChain(f.getSheetID(sheet), axis)
  352. return err
  353. }
  354. if cellData.F != nil {
  355. cellData.F.Content = formula
  356. } else {
  357. cellData.F = &xlsxF{Content: formula}
  358. }
  359. for _, o := range opts {
  360. if o.Type != nil {
  361. cellData.F.T = *o.Type
  362. }
  363. if o.Ref != nil {
  364. cellData.F.Ref = *o.Ref
  365. }
  366. }
  367. return err
  368. }
  369. // GetCellHyperLink provides a function to get cell hyperlink by given
  370. // worksheet name and axis. Boolean type value link will be ture if the cell
  371. // has a hyperlink and the target is the address of the hyperlink. Otherwise,
  372. // the value of link will be false and the value of the target will be a blank
  373. // string. For example get hyperlink of Sheet1!H6:
  374. //
  375. // link, target, err := f.GetCellHyperLink("Sheet1", "H6")
  376. //
  377. func (f *File) GetCellHyperLink(sheet, axis string) (bool, string, error) {
  378. // Check for correct cell name
  379. if _, _, err := SplitCellName(axis); err != nil {
  380. return false, "", err
  381. }
  382. ws, err := f.workSheetReader(sheet)
  383. if err != nil {
  384. return false, "", err
  385. }
  386. axis, err = f.mergeCellsParser(ws, axis)
  387. if err != nil {
  388. return false, "", err
  389. }
  390. if ws.Hyperlinks != nil {
  391. for _, link := range ws.Hyperlinks.Hyperlink {
  392. if link.Ref == axis {
  393. if link.RID != "" {
  394. return true, f.getSheetRelationshipsTargetByID(sheet, link.RID), err
  395. }
  396. return true, link.Location, err
  397. }
  398. }
  399. }
  400. return false, "", err
  401. }
  402. // HyperlinkOpts can be passed to SetCellHyperlink to set optional hyperlink
  403. // attributes (e.g. display value)
  404. type HyperlinkOpts struct {
  405. Display *string
  406. Tooltip *string
  407. }
  408. // SetCellHyperLink provides a function to set cell hyperlink by given
  409. // worksheet name and link URL address. LinkType defines two types of
  410. // hyperlink "External" for web site or "Location" for moving to one of cell
  411. // in this workbook. Maximum limit hyperlinks in a worksheet is 65530. The
  412. // below is example for external link.
  413. //
  414. // err := f.SetCellHyperLink("Sheet1", "A3", "https://github.com/360EntSecGroup-Skylar/excelize", "External")
  415. // // Set underline and font color style for the cell.
  416. // style, err := f.NewStyle(`{"font":{"color":"#1265BE","underline":"single"}}`)
  417. // err = f.SetCellStyle("Sheet1", "A3", "A3", style)
  418. //
  419. // A this is another example for "Location":
  420. //
  421. // err := f.SetCellHyperLink("Sheet1", "A3", "Sheet1!A40", "Location")
  422. //
  423. func (f *File) SetCellHyperLink(sheet, axis, link, linkType string, opts ...HyperlinkOpts) error {
  424. // Check for correct cell name
  425. if _, _, err := SplitCellName(axis); err != nil {
  426. return err
  427. }
  428. ws, err := f.workSheetReader(sheet)
  429. if err != nil {
  430. return err
  431. }
  432. axis, err = f.mergeCellsParser(ws, axis)
  433. if err != nil {
  434. return err
  435. }
  436. var linkData xlsxHyperlink
  437. if ws.Hyperlinks == nil {
  438. ws.Hyperlinks = new(xlsxHyperlinks)
  439. }
  440. if len(ws.Hyperlinks.Hyperlink) > TotalSheetHyperlinks {
  441. return errors.New("over maximum limit hyperlinks in a worksheet")
  442. }
  443. switch linkType {
  444. case "External":
  445. linkData = xlsxHyperlink{
  446. Ref: axis,
  447. }
  448. sheetPath := f.sheetMap[trimSheetName(sheet)]
  449. sheetRels := "xl/worksheets/_rels/" + strings.TrimPrefix(sheetPath, "xl/worksheets/") + ".rels"
  450. rID := f.addRels(sheetRels, SourceRelationshipHyperLink, link, linkType)
  451. linkData.RID = "rId" + strconv.Itoa(rID)
  452. f.addSheetNameSpace(sheet, SourceRelationship)
  453. case "Location":
  454. linkData = xlsxHyperlink{
  455. Ref: axis,
  456. Location: link,
  457. }
  458. default:
  459. return fmt.Errorf("invalid link type %q", linkType)
  460. }
  461. for _, o := range opts {
  462. if o.Display != nil {
  463. linkData.Display = *o.Display
  464. }
  465. if o.Tooltip != nil {
  466. linkData.Tooltip = *o.Tooltip
  467. }
  468. }
  469. ws.Hyperlinks.Hyperlink = append(ws.Hyperlinks.Hyperlink, linkData)
  470. return nil
  471. }
  472. // GetCellRichText provides a function to get rich text of cell by given
  473. // worksheet.
  474. func (f *File) GetCellRichText(sheet, cell string) (runs []RichTextRun, err error) {
  475. ws, err := f.workSheetReader(sheet)
  476. if err != nil {
  477. return
  478. }
  479. cellData, _, _, err := f.prepareCell(ws, sheet, cell)
  480. if err != nil {
  481. return
  482. }
  483. siIdx, err := strconv.Atoi(cellData.V)
  484. if nil != err {
  485. return
  486. }
  487. sst := f.sharedStringsReader()
  488. if len(sst.SI) <= siIdx || siIdx < 0 {
  489. return
  490. }
  491. si := sst.SI[siIdx]
  492. for _, v := range si.R {
  493. run := RichTextRun{
  494. Text: v.T.Val,
  495. }
  496. if nil != v.RPr {
  497. font := Font{Underline: "none"}
  498. font.Bold = v.RPr.B != nil
  499. font.Italic = v.RPr.I != nil
  500. if v.RPr.U != nil {
  501. font.Underline = "single"
  502. if v.RPr.U.Val != nil {
  503. font.Underline = *v.RPr.U.Val
  504. }
  505. }
  506. if v.RPr.RFont != nil && v.RPr.RFont.Val != nil {
  507. font.Family = *v.RPr.RFont.Val
  508. }
  509. if v.RPr.Sz != nil && v.RPr.Sz.Val != nil {
  510. font.Size = *v.RPr.Sz.Val
  511. }
  512. font.Strike = v.RPr.Strike != nil
  513. if nil != v.RPr.Color {
  514. font.Color = strings.TrimPrefix(v.RPr.Color.RGB, "FF")
  515. }
  516. run.Font = &font
  517. }
  518. runs = append(runs, run)
  519. }
  520. return
  521. }
  522. // SetCellRichText provides a function to set cell with rich text by given
  523. // worksheet. For example, set rich text on the A1 cell of the worksheet named
  524. // Sheet1:
  525. //
  526. // package main
  527. //
  528. // import (
  529. // "fmt"
  530. //
  531. // "github.com/360EntSecGroup-Skylar/excelize/v2"
  532. // )
  533. //
  534. // func main() {
  535. // f := excelize.NewFile()
  536. // if err := f.SetRowHeight("Sheet1", 1, 35); err != nil {
  537. // fmt.Println(err)
  538. // return
  539. // }
  540. // if err := f.SetColWidth("Sheet1", "A", "A", 44); err != nil {
  541. // fmt.Println(err)
  542. // return
  543. // }
  544. // if err := f.SetCellRichText("Sheet1", "A1", []excelize.RichTextRun{
  545. // {
  546. // Text: "bold",
  547. // Font: &excelize.Font{
  548. // Bold: true,
  549. // Color: "2354e8",
  550. // Family: "Times New Roman",
  551. // },
  552. // },
  553. // {
  554. // Text: " and ",
  555. // Font: &excelize.Font{
  556. // Family: "Times New Roman",
  557. // },
  558. // },
  559. // {
  560. // Text: " italic",
  561. // Font: &excelize.Font{
  562. // Bold: true,
  563. // Color: "e83723",
  564. // Italic: true,
  565. // Family: "Times New Roman",
  566. // },
  567. // },
  568. // {
  569. // Text: "text with color and font-family,",
  570. // Font: &excelize.Font{
  571. // Bold: true,
  572. // Color: "2354e8",
  573. // Family: "Times New Roman",
  574. // },
  575. // },
  576. // {
  577. // Text: "\r\nlarge text with ",
  578. // Font: &excelize.Font{
  579. // Size: 14,
  580. // Color: "ad23e8",
  581. // },
  582. // },
  583. // {
  584. // Text: "strike",
  585. // Font: &excelize.Font{
  586. // Color: "e89923",
  587. // Strike: true,
  588. // },
  589. // },
  590. // {
  591. // Text: " and ",
  592. // Font: &excelize.Font{
  593. // Size: 14,
  594. // Color: "ad23e8",
  595. // },
  596. // },
  597. // {
  598. // Text: "underline.",
  599. // Font: &excelize.Font{
  600. // Color: "23e833",
  601. // Underline: "single",
  602. // },
  603. // },
  604. // }); err != nil {
  605. // fmt.Println(err)
  606. // return
  607. // }
  608. // style, err := f.NewStyle(&excelize.Style{
  609. // Alignment: &excelize.Alignment{
  610. // WrapText: true,
  611. // },
  612. // })
  613. // if err != nil {
  614. // fmt.Println(err)
  615. // return
  616. // }
  617. // if err := f.SetCellStyle("Sheet1", "A1", "A1", style); err != nil {
  618. // fmt.Println(err)
  619. // return
  620. // }
  621. // if err := f.SaveAs("Book1.xlsx"); err != nil {
  622. // fmt.Println(err)
  623. // }
  624. // }
  625. //
  626. func (f *File) SetCellRichText(sheet, cell string, runs []RichTextRun) error {
  627. ws, err := f.workSheetReader(sheet)
  628. if err != nil {
  629. return err
  630. }
  631. cellData, col, _, err := f.prepareCell(ws, sheet, cell)
  632. if err != nil {
  633. return err
  634. }
  635. cellData.S = f.prepareCellStyle(ws, col, cellData.S)
  636. si := xlsxSI{}
  637. sst := f.sharedStringsReader()
  638. textRuns := []xlsxR{}
  639. for _, textRun := range runs {
  640. run := xlsxR{T: &xlsxT{Val: textRun.Text}}
  641. if strings.ContainsAny(textRun.Text, "\r\n ") {
  642. run.T.Space = xml.Attr{Name: xml.Name{Space: NameSpaceXML, Local: "space"}, Value: "preserve"}
  643. }
  644. fnt := textRun.Font
  645. if fnt != nil {
  646. rpr := xlsxRPr{}
  647. trueVal := ""
  648. if fnt.Bold {
  649. rpr.B = &trueVal
  650. }
  651. if fnt.Italic {
  652. rpr.I = &trueVal
  653. }
  654. if fnt.Strike {
  655. rpr.Strike = &trueVal
  656. }
  657. if fnt.Underline != "" {
  658. rpr.U = &attrValString{Val: &fnt.Underline}
  659. }
  660. if fnt.Family != "" {
  661. rpr.RFont = &attrValString{Val: &fnt.Family}
  662. }
  663. if fnt.Size > 0.0 {
  664. rpr.Sz = &attrValFloat{Val: &fnt.Size}
  665. }
  666. if fnt.Color != "" {
  667. rpr.Color = &xlsxColor{RGB: getPaletteColor(fnt.Color)}
  668. }
  669. run.RPr = &rpr
  670. }
  671. textRuns = append(textRuns, run)
  672. }
  673. si.R = textRuns
  674. for idx, strItem := range sst.SI {
  675. if reflect.DeepEqual(strItem, si) {
  676. cellData.T, cellData.V = "s", strconv.Itoa(idx)
  677. return err
  678. }
  679. }
  680. sst.SI = append(sst.SI, si)
  681. sst.Count++
  682. sst.UniqueCount++
  683. cellData.T, cellData.V = "s", strconv.Itoa(len(sst.SI)-1)
  684. return err
  685. }
  686. // SetSheetRow writes an array to row by given worksheet name, starting
  687. // coordinate and a pointer to array type 'slice'. For example, writes an
  688. // array to row 6 start with the cell B6 on Sheet1:
  689. //
  690. // err := f.SetSheetRow("Sheet1", "B6", &[]interface{}{"1", nil, 2})
  691. //
  692. func (f *File) SetSheetRow(sheet, axis string, slice interface{}) error {
  693. col, row, err := CellNameToCoordinates(axis)
  694. if err != nil {
  695. return err
  696. }
  697. // Make sure 'slice' is a Ptr to Slice
  698. v := reflect.ValueOf(slice)
  699. if v.Kind() != reflect.Ptr || v.Elem().Kind() != reflect.Slice {
  700. return errors.New("pointer to slice expected")
  701. }
  702. v = v.Elem()
  703. for i := 0; i < v.Len(); i++ {
  704. cell, err := CoordinatesToCellName(col+i, row)
  705. // Error should never happens here. But keep checking to early detect regresions
  706. // if it will be introduced in future.
  707. if err != nil {
  708. return err
  709. }
  710. if err := f.SetCellValue(sheet, cell, v.Index(i).Interface()); err != nil {
  711. return err
  712. }
  713. }
  714. return err
  715. }
  716. // getCellInfo does common preparation for all SetCell* methods.
  717. func (f *File) prepareCell(ws *xlsxWorksheet, sheet, cell string) (*xlsxC, int, int, error) {
  718. ws.Lock()
  719. defer ws.Unlock()
  720. var err error
  721. cell, err = f.mergeCellsParser(ws, cell)
  722. if err != nil {
  723. return nil, 0, 0, err
  724. }
  725. col, row, err := CellNameToCoordinates(cell)
  726. if err != nil {
  727. return nil, 0, 0, err
  728. }
  729. prepareSheetXML(ws, col, row)
  730. return &ws.SheetData.Row[row-1].C[col-1], col, row, err
  731. }
  732. // getCellStringFunc does common value extraction workflow for all GetCell*
  733. // methods. Passed function implements specific part of required logic.
  734. func (f *File) getCellStringFunc(sheet, axis string, fn func(x *xlsxWorksheet, c *xlsxC) (string, bool, error)) (string, error) {
  735. ws, err := f.workSheetReader(sheet)
  736. if err != nil {
  737. return "", err
  738. }
  739. axis, err = f.mergeCellsParser(ws, axis)
  740. if err != nil {
  741. return "", err
  742. }
  743. _, row, err := CellNameToCoordinates(axis)
  744. if err != nil {
  745. return "", err
  746. }
  747. ws.Lock()
  748. defer ws.Unlock()
  749. lastRowNum := 0
  750. if l := len(ws.SheetData.Row); l > 0 {
  751. lastRowNum = ws.SheetData.Row[l-1].R
  752. }
  753. // keep in mind: row starts from 1
  754. if row > lastRowNum {
  755. return "", nil
  756. }
  757. for rowIdx := range ws.SheetData.Row {
  758. rowData := &ws.SheetData.Row[rowIdx]
  759. if rowData.R != row {
  760. continue
  761. }
  762. for colIdx := range rowData.C {
  763. colData := &rowData.C[colIdx]
  764. if axis != colData.R {
  765. continue
  766. }
  767. val, ok, err := fn(ws, colData)
  768. if err != nil {
  769. return "", err
  770. }
  771. if ok {
  772. return val, nil
  773. }
  774. }
  775. }
  776. return "", nil
  777. }
  778. // formattedValue provides a function to returns a value after formatted. If
  779. // it is possible to apply a format to the cell value, it will do so, if not
  780. // then an error will be returned, along with the raw value of the cell.
  781. func (f *File) formattedValue(s int, v string) string {
  782. if s == 0 {
  783. return v
  784. }
  785. styleSheet := f.stylesReader()
  786. if s >= len(styleSheet.CellXfs.Xf) {
  787. return v
  788. }
  789. var numFmtID int
  790. if styleSheet.CellXfs.Xf[s].NumFmtID != nil {
  791. numFmtID = *styleSheet.CellXfs.Xf[s].NumFmtID
  792. }
  793. ok := builtInNumFmtFunc[numFmtID]
  794. if ok != nil {
  795. return ok(v, builtInNumFmt[numFmtID])
  796. }
  797. if styleSheet == nil || styleSheet.NumFmts == nil {
  798. return v
  799. }
  800. for _, xlsxFmt := range styleSheet.NumFmts.NumFmt {
  801. if xlsxFmt.NumFmtID == numFmtID {
  802. format := strings.ToLower(xlsxFmt.FormatCode)
  803. if strings.Contains(format, "y") || strings.Contains(format, "m") || strings.Contains(strings.Replace(format, "red", "", -1), "d") || strings.Contains(format, "h") {
  804. return parseTime(v, format)
  805. }
  806. return v
  807. }
  808. }
  809. return v
  810. }
  811. // prepareCellStyle provides a function to prepare style index of cell in
  812. // worksheet by given column index and style index.
  813. func (f *File) prepareCellStyle(ws *xlsxWorksheet, col, style int) int {
  814. if ws.Cols != nil && style == 0 {
  815. for _, c := range ws.Cols.Col {
  816. if c.Min <= col && col <= c.Max {
  817. style = c.Style
  818. }
  819. }
  820. }
  821. return style
  822. }
  823. // mergeCellsParser provides a function to check merged cells in worksheet by
  824. // given axis.
  825. func (f *File) mergeCellsParser(ws *xlsxWorksheet, axis string) (string, error) {
  826. axis = strings.ToUpper(axis)
  827. if ws.MergeCells != nil {
  828. for i := 0; i < len(ws.MergeCells.Cells); i++ {
  829. ok, err := f.checkCellInArea(axis, ws.MergeCells.Cells[i].Ref)
  830. if err != nil {
  831. return axis, err
  832. }
  833. if ok {
  834. axis = strings.Split(ws.MergeCells.Cells[i].Ref, ":")[0]
  835. }
  836. }
  837. }
  838. return axis, nil
  839. }
  840. // checkCellInArea provides a function to determine if a given coordinate is
  841. // within an area.
  842. func (f *File) checkCellInArea(cell, area string) (bool, error) {
  843. col, row, err := CellNameToCoordinates(cell)
  844. if err != nil {
  845. return false, err
  846. }
  847. rng := strings.Split(area, ":")
  848. if len(rng) != 2 {
  849. return false, err
  850. }
  851. coordinates, err := f.areaRefToCoordinates(area)
  852. if err != nil {
  853. return false, err
  854. }
  855. return cellInRef([]int{col, row}, coordinates), err
  856. }
  857. // cellInRef provides a function to determine if a given range is within an
  858. // range.
  859. func cellInRef(cell, ref []int) bool {
  860. return cell[0] >= ref[0] && cell[0] <= ref[2] && cell[1] >= ref[1] && cell[1] <= ref[3]
  861. }
  862. // isOverlap find if the given two rectangles overlap or not.
  863. func isOverlap(rect1, rect2 []int) bool {
  864. return cellInRef([]int{rect1[0], rect1[1]}, rect2) ||
  865. cellInRef([]int{rect1[2], rect1[1]}, rect2) ||
  866. cellInRef([]int{rect1[0], rect1[3]}, rect2) ||
  867. cellInRef([]int{rect1[2], rect1[3]}, rect2) ||
  868. cellInRef([]int{rect2[0], rect2[1]}, rect1) ||
  869. cellInRef([]int{rect2[2], rect2[1]}, rect1) ||
  870. cellInRef([]int{rect2[0], rect2[3]}, rect1) ||
  871. cellInRef([]int{rect2[2], rect2[3]}, rect1)
  872. }
  873. // getSharedForumula find a cell contains the same formula as another cell,
  874. // the "shared" value can be used for the t attribute and the si attribute can
  875. // be used to refer to the cell containing the formula. Two formulas are
  876. // considered to be the same when their respective representations in
  877. // R1C1-reference notation, are the same.
  878. //
  879. // Note that this function not validate ref tag to check the cell if or not in
  880. // allow area, and always return origin shared formula.
  881. func getSharedForumula(ws *xlsxWorksheet, si string) string {
  882. for _, r := range ws.SheetData.Row {
  883. for _, c := range r.C {
  884. if c.F != nil && c.F.Ref != "" && c.F.T == STCellFormulaTypeShared && c.F.Si == si {
  885. return c.F.Content
  886. }
  887. }
  888. }
  889. return ""
  890. }