cell.go 26 KB

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