cell.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880
  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 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. "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 XLSX file. If it is possible to apply a format
  33. // to the cell value, it will do so, if not then an error will be returned,
  34. // along with the raw value of the cell.
  35. func (f *File) GetCellValue(sheet, axis string) (string, error) {
  36. return f.getCellStringFunc(sheet, axis, func(x *xlsxWorksheet, c *xlsxC) (string, bool, error) {
  37. val, err := c.getValueFrom(f, f.sharedStringsReader())
  38. return val, true, err
  39. })
  40. }
  41. // SetCellValue provides a function to set 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. // SetCellHyperLink provides a function to set cell hyperlink by given
  403. // worksheet name and link URL address. LinkType defines two types of
  404. // hyperlink "External" for web site or "Location" for moving to one of cell
  405. // in this workbook. Maximum limit hyperlinks in a worksheet is 65530. The
  406. // below is example for external link.
  407. //
  408. // err := f.SetCellHyperLink("Sheet1", "A3", "https://github.com/360EntSecGroup-Skylar/excelize", "External")
  409. // // Set underline and font color style for the cell.
  410. // style, err := f.NewStyle(`{"font":{"color":"#1265BE","underline":"single"}}`)
  411. // err = f.SetCellStyle("Sheet1", "A3", "A3", style)
  412. //
  413. // A this is another example for "Location":
  414. //
  415. // err := f.SetCellHyperLink("Sheet1", "A3", "Sheet1!A40", "Location")
  416. //
  417. func (f *File) SetCellHyperLink(sheet, axis, link, linkType string) error {
  418. // Check for correct cell name
  419. if _, _, err := SplitCellName(axis); err != nil {
  420. return err
  421. }
  422. ws, err := f.workSheetReader(sheet)
  423. if err != nil {
  424. return err
  425. }
  426. axis, err = f.mergeCellsParser(ws, axis)
  427. if err != nil {
  428. return err
  429. }
  430. var linkData xlsxHyperlink
  431. if ws.Hyperlinks == nil {
  432. ws.Hyperlinks = new(xlsxHyperlinks)
  433. }
  434. if len(ws.Hyperlinks.Hyperlink) > TotalSheetHyperlinks {
  435. return errors.New("over maximum limit hyperlinks in a worksheet")
  436. }
  437. switch linkType {
  438. case "External":
  439. linkData = xlsxHyperlink{
  440. Ref: axis,
  441. }
  442. sheetPath := f.sheetMap[trimSheetName(sheet)]
  443. sheetRels := "xl/worksheets/_rels/" + strings.TrimPrefix(sheetPath, "xl/worksheets/") + ".rels"
  444. rID := f.addRels(sheetRels, SourceRelationshipHyperLink, link, linkType)
  445. linkData.RID = "rId" + strconv.Itoa(rID)
  446. f.addSheetNameSpace(sheet, SourceRelationship)
  447. case "Location":
  448. linkData = xlsxHyperlink{
  449. Ref: axis,
  450. Location: link,
  451. }
  452. default:
  453. return fmt.Errorf("invalid link type %q", linkType)
  454. }
  455. ws.Hyperlinks.Hyperlink = append(ws.Hyperlinks.Hyperlink, linkData)
  456. return nil
  457. }
  458. // SetCellRichText provides a function to set cell with rich text by given
  459. // worksheet. For example, set rich text on the A1 cell of the worksheet named
  460. // Sheet1:
  461. //
  462. // package main
  463. //
  464. // import (
  465. // "fmt"
  466. //
  467. // "github.com/360EntSecGroup-Skylar/excelize/v2"
  468. // )
  469. //
  470. // func main() {
  471. // f := excelize.NewFile()
  472. // if err := f.SetRowHeight("Sheet1", 1, 35); err != nil {
  473. // fmt.Println(err)
  474. // return
  475. // }
  476. // if err := f.SetColWidth("Sheet1", "A", "A", 44); err != nil {
  477. // fmt.Println(err)
  478. // return
  479. // }
  480. // if err := f.SetCellRichText("Sheet1", "A1", []excelize.RichTextRun{
  481. // {
  482. // Text: "bold",
  483. // Font: &excelize.Font{
  484. // Bold: true,
  485. // Color: "2354e8",
  486. // Family: "Times New Roman",
  487. // },
  488. // },
  489. // {
  490. // Text: " and ",
  491. // Font: &excelize.Font{
  492. // Family: "Times New Roman",
  493. // },
  494. // },
  495. // {
  496. // Text: " italic",
  497. // Font: &excelize.Font{
  498. // Bold: true,
  499. // Color: "e83723",
  500. // Italic: true,
  501. // Family: "Times New Roman",
  502. // },
  503. // },
  504. // {
  505. // Text: "text with color and font-family,",
  506. // Font: &excelize.Font{
  507. // Bold: true,
  508. // Color: "2354e8",
  509. // Family: "Times New Roman",
  510. // },
  511. // },
  512. // {
  513. // Text: "\r\nlarge text with ",
  514. // Font: &excelize.Font{
  515. // Size: 14,
  516. // Color: "ad23e8",
  517. // },
  518. // },
  519. // {
  520. // Text: "strike",
  521. // Font: &excelize.Font{
  522. // Color: "e89923",
  523. // Strike: true,
  524. // },
  525. // },
  526. // {
  527. // Text: " and ",
  528. // Font: &excelize.Font{
  529. // Size: 14,
  530. // Color: "ad23e8",
  531. // },
  532. // },
  533. // {
  534. // Text: "underline.",
  535. // Font: &excelize.Font{
  536. // Color: "23e833",
  537. // Underline: "single",
  538. // },
  539. // },
  540. // }); err != nil {
  541. // fmt.Println(err)
  542. // return
  543. // }
  544. // style, err := f.NewStyle(&excelize.Style{
  545. // Alignment: &excelize.Alignment{
  546. // WrapText: true,
  547. // },
  548. // })
  549. // if err != nil {
  550. // fmt.Println(err)
  551. // return
  552. // }
  553. // if err := f.SetCellStyle("Sheet1", "A1", "A1", style); err != nil {
  554. // fmt.Println(err)
  555. // return
  556. // }
  557. // if err := f.SaveAs("Book1.xlsx"); err != nil {
  558. // fmt.Println(err)
  559. // }
  560. // }
  561. //
  562. func (f *File) SetCellRichText(sheet, cell string, runs []RichTextRun) error {
  563. ws, err := f.workSheetReader(sheet)
  564. if err != nil {
  565. return err
  566. }
  567. cellData, col, _, err := f.prepareCell(ws, sheet, cell)
  568. if err != nil {
  569. return err
  570. }
  571. cellData.S = f.prepareCellStyle(ws, col, cellData.S)
  572. si := xlsxSI{}
  573. sst := f.sharedStringsReader()
  574. textRuns := []xlsxR{}
  575. for _, textRun := range runs {
  576. run := xlsxR{T: &xlsxT{Val: textRun.Text}}
  577. if strings.ContainsAny(textRun.Text, "\r\n ") {
  578. run.T.Space = xml.Attr{Name: xml.Name{Space: NameSpaceXML, Local: "space"}, Value: "preserve"}
  579. }
  580. fnt := textRun.Font
  581. if fnt != nil {
  582. rpr := xlsxRPr{}
  583. if fnt.Bold {
  584. rpr.B = " "
  585. }
  586. if fnt.Italic {
  587. rpr.I = " "
  588. }
  589. if fnt.Strike {
  590. rpr.Strike = " "
  591. }
  592. if fnt.Underline != "" {
  593. rpr.U = &attrValString{Val: &fnt.Underline}
  594. }
  595. if fnt.Family != "" {
  596. rpr.RFont = &attrValString{Val: &fnt.Family}
  597. }
  598. if fnt.Size > 0.0 {
  599. rpr.Sz = &attrValFloat{Val: &fnt.Size}
  600. }
  601. if fnt.Color != "" {
  602. rpr.Color = &xlsxColor{RGB: getPaletteColor(fnt.Color)}
  603. }
  604. run.RPr = &rpr
  605. }
  606. textRuns = append(textRuns, run)
  607. }
  608. si.R = textRuns
  609. sst.SI = append(sst.SI, si)
  610. sst.Count++
  611. sst.UniqueCount++
  612. cellData.T, cellData.V = "s", strconv.Itoa(len(sst.SI)-1)
  613. return err
  614. }
  615. // SetSheetRow writes an array to row by given worksheet name, starting
  616. // coordinate and a pointer to array type 'slice'. For example, writes an
  617. // array to row 6 start with the cell B6 on Sheet1:
  618. //
  619. // err := f.SetSheetRow("Sheet1", "B6", &[]interface{}{"1", nil, 2})
  620. //
  621. func (f *File) SetSheetRow(sheet, axis string, slice interface{}) error {
  622. col, row, err := CellNameToCoordinates(axis)
  623. if err != nil {
  624. return err
  625. }
  626. // Make sure 'slice' is a Ptr to Slice
  627. v := reflect.ValueOf(slice)
  628. if v.Kind() != reflect.Ptr || v.Elem().Kind() != reflect.Slice {
  629. return errors.New("pointer to slice expected")
  630. }
  631. v = v.Elem()
  632. for i := 0; i < v.Len(); i++ {
  633. cell, err := CoordinatesToCellName(col+i, row)
  634. // Error should never happens here. But keep checking to early detect regresions
  635. // if it will be introduced in future.
  636. if err != nil {
  637. return err
  638. }
  639. if err := f.SetCellValue(sheet, cell, v.Index(i).Interface()); err != nil {
  640. return err
  641. }
  642. }
  643. return err
  644. }
  645. // getCellInfo does common preparation for all SetCell* methods.
  646. func (f *File) prepareCell(ws *xlsxWorksheet, sheet, cell string) (*xlsxC, int, int, error) {
  647. ws.Lock()
  648. defer ws.Unlock()
  649. var err error
  650. cell, err = f.mergeCellsParser(ws, cell)
  651. if err != nil {
  652. return nil, 0, 0, err
  653. }
  654. col, row, err := CellNameToCoordinates(cell)
  655. if err != nil {
  656. return nil, 0, 0, err
  657. }
  658. prepareSheetXML(ws, col, row)
  659. return &ws.SheetData.Row[row-1].C[col-1], col, row, err
  660. }
  661. // getCellStringFunc does common value extraction workflow for all GetCell*
  662. // methods. Passed function implements specific part of required logic.
  663. func (f *File) getCellStringFunc(sheet, axis string, fn func(x *xlsxWorksheet, c *xlsxC) (string, bool, error)) (string, error) {
  664. ws, err := f.workSheetReader(sheet)
  665. if err != nil {
  666. return "", err
  667. }
  668. axis, err = f.mergeCellsParser(ws, axis)
  669. if err != nil {
  670. return "", err
  671. }
  672. _, row, err := CellNameToCoordinates(axis)
  673. if err != nil {
  674. return "", err
  675. }
  676. ws.Lock()
  677. defer ws.Unlock()
  678. lastRowNum := 0
  679. if l := len(ws.SheetData.Row); l > 0 {
  680. lastRowNum = ws.SheetData.Row[l-1].R
  681. }
  682. // keep in mind: row starts from 1
  683. if row > lastRowNum {
  684. return "", nil
  685. }
  686. for rowIdx := range ws.SheetData.Row {
  687. rowData := &ws.SheetData.Row[rowIdx]
  688. if rowData.R != row {
  689. continue
  690. }
  691. for colIdx := range rowData.C {
  692. colData := &rowData.C[colIdx]
  693. if axis != colData.R {
  694. continue
  695. }
  696. val, ok, err := fn(ws, colData)
  697. if err != nil {
  698. return "", err
  699. }
  700. if ok {
  701. return val, nil
  702. }
  703. }
  704. }
  705. return "", nil
  706. }
  707. // formattedValue provides a function to returns a value after formatted. If
  708. // it is possible to apply a format to the cell value, it will do so, if not
  709. // then an error will be returned, along with the raw value of the cell.
  710. func (f *File) formattedValue(s int, v string) string {
  711. if s == 0 {
  712. return v
  713. }
  714. styleSheet := f.stylesReader()
  715. if s >= len(styleSheet.CellXfs.Xf) {
  716. return v
  717. }
  718. var numFmtID int
  719. if styleSheet.CellXfs.Xf[s].NumFmtID != nil {
  720. numFmtID = *styleSheet.CellXfs.Xf[s].NumFmtID
  721. }
  722. ok := builtInNumFmtFunc[numFmtID]
  723. if ok != nil {
  724. return ok(v, builtInNumFmt[numFmtID])
  725. }
  726. if styleSheet == nil || styleSheet.NumFmts == nil {
  727. return v
  728. }
  729. for _, xlsxFmt := range styleSheet.NumFmts.NumFmt {
  730. if xlsxFmt.NumFmtID == numFmtID {
  731. format := strings.ToLower(xlsxFmt.FormatCode)
  732. if strings.Contains(format, "y") || strings.Contains(format, "m") || strings.Contains(strings.Replace(format, "red", "", -1), "d") || strings.Contains(format, "h") {
  733. return parseTime(v, format)
  734. }
  735. return v
  736. }
  737. }
  738. return v
  739. }
  740. // prepareCellStyle provides a function to prepare style index of cell in
  741. // worksheet by given column index and style index.
  742. func (f *File) prepareCellStyle(ws *xlsxWorksheet, col, style int) int {
  743. if ws.Cols != nil && style == 0 {
  744. for _, c := range ws.Cols.Col {
  745. if c.Min <= col && col <= c.Max {
  746. style = c.Style
  747. }
  748. }
  749. }
  750. return style
  751. }
  752. // mergeCellsParser provides a function to check merged cells in worksheet by
  753. // given axis.
  754. func (f *File) mergeCellsParser(ws *xlsxWorksheet, axis string) (string, error) {
  755. axis = strings.ToUpper(axis)
  756. if ws.MergeCells != nil {
  757. for i := 0; i < len(ws.MergeCells.Cells); i++ {
  758. ok, err := f.checkCellInArea(axis, ws.MergeCells.Cells[i].Ref)
  759. if err != nil {
  760. return axis, err
  761. }
  762. if ok {
  763. axis = strings.Split(ws.MergeCells.Cells[i].Ref, ":")[0]
  764. }
  765. }
  766. }
  767. return axis, nil
  768. }
  769. // checkCellInArea provides a function to determine if a given coordinate is
  770. // within an area.
  771. func (f *File) checkCellInArea(cell, area string) (bool, error) {
  772. col, row, err := CellNameToCoordinates(cell)
  773. if err != nil {
  774. return false, err
  775. }
  776. rng := strings.Split(area, ":")
  777. if len(rng) != 2 {
  778. return false, err
  779. }
  780. coordinates, err := f.areaRefToCoordinates(area)
  781. if err != nil {
  782. return false, err
  783. }
  784. return cellInRef([]int{col, row}, coordinates), err
  785. }
  786. // cellInRef provides a function to determine if a given range is within an
  787. // range.
  788. func cellInRef(cell, ref []int) bool {
  789. return cell[0] >= ref[0] && cell[0] <= ref[2] && cell[1] >= ref[1] && cell[1] <= ref[3]
  790. }
  791. // isOverlap find if the given two rectangles overlap or not.
  792. func isOverlap(rect1, rect2 []int) bool {
  793. return cellInRef([]int{rect1[0], rect1[1]}, rect2) ||
  794. cellInRef([]int{rect1[2], rect1[1]}, rect2) ||
  795. cellInRef([]int{rect1[0], rect1[3]}, rect2) ||
  796. cellInRef([]int{rect1[2], rect1[3]}, rect2) ||
  797. cellInRef([]int{rect2[0], rect2[1]}, rect1) ||
  798. cellInRef([]int{rect2[2], rect2[1]}, rect1) ||
  799. cellInRef([]int{rect2[0], rect2[3]}, rect1) ||
  800. cellInRef([]int{rect2[2], rect2[3]}, rect1)
  801. }
  802. // getSharedForumula find a cell contains the same formula as another cell,
  803. // the "shared" value can be used for the t attribute and the si attribute can
  804. // be used to refer to the cell containing the formula. Two formulas are
  805. // considered to be the same when their respective representations in
  806. // R1C1-reference notation, are the same.
  807. //
  808. // Note that this function not validate ref tag to check the cell if or not in
  809. // allow area, and always return origin shared formula.
  810. func getSharedForumula(ws *xlsxWorksheet, si string) string {
  811. for _, r := range ws.SheetData.Row {
  812. for _, c := range r.C {
  813. if c.F != nil && c.F.Ref != "" && c.F.T == STCellFormulaTypeShared && c.F.Si == si {
  814. return c.F.Content
  815. }
  816. }
  817. }
  818. return ""
  819. }