cell.go 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549
  1. // Copyright 2016 - 2023 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 and
  6. // read from XLAM / XLSM / XLSX / XLTM / XLTX files. Supports reading and
  7. // writing spreadsheet documents generated by Microsoft Excel™ 2007 and later.
  8. // Supports complex components by high compatibility, and provided streaming
  9. // API for generating or reading data from a worksheet with huge amounts of
  10. // data. This library needs Go version 1.16 or later.
  11. package excelize
  12. import (
  13. "bytes"
  14. "encoding/xml"
  15. "fmt"
  16. "os"
  17. "reflect"
  18. "strconv"
  19. "strings"
  20. "time"
  21. )
  22. // CellType is the type of cell value type.
  23. type CellType byte
  24. // Cell value types enumeration.
  25. const (
  26. CellTypeUnset CellType = iota
  27. CellTypeBool
  28. CellTypeDate
  29. CellTypeError
  30. CellTypeFormula
  31. CellTypeInlineString
  32. CellTypeNumber
  33. CellTypeSharedString
  34. )
  35. const (
  36. // STCellFormulaTypeArray defined the formula is an array formula.
  37. STCellFormulaTypeArray = "array"
  38. // STCellFormulaTypeDataTable defined the formula is a data table formula.
  39. STCellFormulaTypeDataTable = "dataTable"
  40. // STCellFormulaTypeNormal defined the formula is a regular cell formula.
  41. STCellFormulaTypeNormal = "normal"
  42. // STCellFormulaTypeShared defined the formula is part of a shared formula.
  43. STCellFormulaTypeShared = "shared"
  44. )
  45. // cellTypes mapping the cell's data type and enumeration.
  46. var cellTypes = map[string]CellType{
  47. "b": CellTypeBool,
  48. "d": CellTypeDate,
  49. "n": CellTypeNumber,
  50. "e": CellTypeError,
  51. "s": CellTypeSharedString,
  52. "str": CellTypeFormula,
  53. "inlineStr": CellTypeInlineString,
  54. }
  55. // GetCellValue provides a function to get formatted value from cell by given
  56. // worksheet name and cell reference in spreadsheet. The return value is
  57. // converted to the 'string' data type. This function is concurrency safe. If
  58. // the cell format can be applied to the value of a cell, the applied value
  59. // will be returned, otherwise the original value will be returned. All cells'
  60. // values will be the same in a merged range.
  61. func (f *File) GetCellValue(sheet, cell string, opts ...Options) (string, error) {
  62. return f.getCellStringFunc(sheet, cell, func(x *xlsxWorksheet, c *xlsxC) (string, bool, error) {
  63. sst, err := f.sharedStringsReader()
  64. if err != nil {
  65. return "", true, err
  66. }
  67. val, err := c.getValueFrom(f, sst, getOptions(opts...).RawCellValue)
  68. return val, true, err
  69. })
  70. }
  71. // GetCellType provides a function to get the cell's data type by given
  72. // worksheet name and cell reference in spreadsheet file.
  73. func (f *File) GetCellType(sheet, cell string) (CellType, error) {
  74. var (
  75. err error
  76. cellTypeStr string
  77. cellType CellType
  78. )
  79. if cellTypeStr, err = f.getCellStringFunc(sheet, cell, func(x *xlsxWorksheet, c *xlsxC) (string, bool, error) {
  80. return c.T, true, nil
  81. }); err != nil {
  82. return CellTypeUnset, err
  83. }
  84. cellType = cellTypes[cellTypeStr]
  85. return cellType, err
  86. }
  87. // SetCellValue provides a function to set the value of a cell. This function
  88. // is concurrency safe. The specified coordinates should not be in the first
  89. // row of the table, a complex number can be set with string text. The
  90. // following shows the supported data types:
  91. //
  92. // int
  93. // int8
  94. // int16
  95. // int32
  96. // int64
  97. // uint
  98. // uint8
  99. // uint16
  100. // uint32
  101. // uint64
  102. // float32
  103. // float64
  104. // string
  105. // []byte
  106. // time.Duration
  107. // time.Time
  108. // bool
  109. // nil
  110. //
  111. // Note that default date format is m/d/yy h:mm of time.Time type value. You
  112. // can set numbers format by the SetCellStyle function. If you need to set the
  113. // specialized date in Excel like January 0, 1900 or February 29, 1900, these
  114. // times can not representation in Go language time.Time data type. Please set
  115. // the cell value as number 0 or 60, then create and bind the date-time number
  116. // format style for the cell.
  117. func (f *File) SetCellValue(sheet, cell string, value interface{}) error {
  118. var err error
  119. switch v := value.(type) {
  120. case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
  121. err = f.setCellIntFunc(sheet, cell, v)
  122. case float32:
  123. err = f.SetCellFloat(sheet, cell, float64(v), -1, 32)
  124. case float64:
  125. err = f.SetCellFloat(sheet, cell, v, -1, 64)
  126. case string:
  127. err = f.SetCellStr(sheet, cell, v)
  128. case []byte:
  129. err = f.SetCellStr(sheet, cell, string(v))
  130. case time.Duration:
  131. _, d := setCellDuration(v)
  132. err = f.SetCellDefault(sheet, cell, d)
  133. if err != nil {
  134. return err
  135. }
  136. err = f.setDefaultTimeStyle(sheet, cell, 21)
  137. case time.Time:
  138. err = f.setCellTimeFunc(sheet, cell, v)
  139. case bool:
  140. err = f.SetCellBool(sheet, cell, v)
  141. case nil:
  142. err = f.SetCellDefault(sheet, cell, "")
  143. default:
  144. err = f.SetCellStr(sheet, cell, fmt.Sprint(value))
  145. }
  146. return err
  147. }
  148. // String extracts characters from a string item.
  149. func (x xlsxSI) String() string {
  150. var value strings.Builder
  151. if x.T != nil {
  152. value.WriteString(x.T.Val)
  153. }
  154. for _, s := range x.R {
  155. if s.T != nil {
  156. value.WriteString(s.T.Val)
  157. }
  158. }
  159. if value.Len() == 0 {
  160. return ""
  161. }
  162. return bstrUnmarshal(value.String())
  163. }
  164. // hasValue determine if cell non-blank value.
  165. func (c *xlsxC) hasValue() bool {
  166. return c.S != 0 || c.V != "" || c.F != nil || c.T != ""
  167. }
  168. // removeFormula delete formula for the cell.
  169. func (f *File) removeFormula(c *xlsxC, ws *xlsxWorksheet, sheet string) error {
  170. if c.F != nil && c.Vm == nil {
  171. sheetID := f.getSheetID(sheet)
  172. if err := f.deleteCalcChain(sheetID, c.R); err != nil {
  173. return err
  174. }
  175. if c.F.T == STCellFormulaTypeShared && c.F.Ref != "" {
  176. si := c.F.Si
  177. for r, row := range ws.SheetData.Row {
  178. for col, cell := range row.C {
  179. if cell.F != nil && cell.F.Si != nil && *cell.F.Si == *si {
  180. ws.SheetData.Row[r].C[col].F = nil
  181. _ = f.deleteCalcChain(sheetID, cell.R)
  182. }
  183. }
  184. }
  185. }
  186. c.F = nil
  187. }
  188. return nil
  189. }
  190. // setCellIntFunc is a wrapper of SetCellInt.
  191. func (f *File) setCellIntFunc(sheet, cell string, value interface{}) error {
  192. var err error
  193. switch v := value.(type) {
  194. case int:
  195. err = f.SetCellInt(sheet, cell, v)
  196. case int8:
  197. err = f.SetCellInt(sheet, cell, int(v))
  198. case int16:
  199. err = f.SetCellInt(sheet, cell, int(v))
  200. case int32:
  201. err = f.SetCellInt(sheet, cell, int(v))
  202. case int64:
  203. err = f.SetCellInt(sheet, cell, int(v))
  204. case uint:
  205. err = f.SetCellInt(sheet, cell, int(v))
  206. case uint8:
  207. err = f.SetCellInt(sheet, cell, int(v))
  208. case uint16:
  209. err = f.SetCellInt(sheet, cell, int(v))
  210. case uint32:
  211. err = f.SetCellInt(sheet, cell, int(v))
  212. case uint64:
  213. err = f.SetCellInt(sheet, cell, int(v))
  214. }
  215. return err
  216. }
  217. // setCellTimeFunc provides a method to process time type of value for
  218. // SetCellValue.
  219. func (f *File) setCellTimeFunc(sheet, cell string, value time.Time) error {
  220. ws, err := f.workSheetReader(sheet)
  221. if err != nil {
  222. return err
  223. }
  224. c, col, row, err := f.prepareCell(ws, cell)
  225. if err != nil {
  226. return err
  227. }
  228. ws.Lock()
  229. c.S = f.prepareCellStyle(ws, col, row, c.S)
  230. ws.Unlock()
  231. var date1904, isNum bool
  232. wb, err := f.workbookReader()
  233. if err != nil {
  234. return err
  235. }
  236. if wb != nil && wb.WorkbookPr != nil {
  237. date1904 = wb.WorkbookPr.Date1904
  238. }
  239. if isNum, err = c.setCellTime(value, date1904); err != nil {
  240. return err
  241. }
  242. if isNum {
  243. _ = f.setDefaultTimeStyle(sheet, cell, 22)
  244. }
  245. return err
  246. }
  247. // setCellTime prepares cell type and Excel time by given Go time.Time type
  248. // timestamp.
  249. func (c *xlsxC) setCellTime(value time.Time, date1904 bool) (isNum bool, err error) {
  250. var excelTime float64
  251. _, offset := value.In(value.Location()).Zone()
  252. value = value.Add(time.Duration(offset) * time.Second)
  253. if excelTime, err = timeToExcelTime(value, date1904); err != nil {
  254. return
  255. }
  256. isNum = excelTime > 0
  257. if isNum {
  258. c.setCellDefault(strconv.FormatFloat(excelTime, 'f', -1, 64))
  259. } else {
  260. c.setCellDefault(value.Format(time.RFC3339Nano))
  261. }
  262. return
  263. }
  264. // setCellDuration prepares cell type and value by given Go time.Duration type
  265. // time duration.
  266. func setCellDuration(value time.Duration) (t string, v string) {
  267. v = strconv.FormatFloat(value.Seconds()/86400, 'f', -1, 32)
  268. return
  269. }
  270. // SetCellInt provides a function to set int type value of a cell by given
  271. // worksheet name, cell reference and cell value.
  272. func (f *File) SetCellInt(sheet, cell string, value int) error {
  273. ws, err := f.workSheetReader(sheet)
  274. if err != nil {
  275. return err
  276. }
  277. c, col, row, err := f.prepareCell(ws, cell)
  278. if err != nil {
  279. return err
  280. }
  281. ws.Lock()
  282. defer ws.Unlock()
  283. c.S = f.prepareCellStyle(ws, col, row, c.S)
  284. c.T, c.V = setCellInt(value)
  285. c.IS = nil
  286. return f.removeFormula(c, ws, sheet)
  287. }
  288. // setCellInt prepares cell type and string type cell value by a given
  289. // integer.
  290. func setCellInt(value int) (t string, v string) {
  291. v = strconv.Itoa(value)
  292. return
  293. }
  294. // SetCellBool provides a function to set bool type value of a cell by given
  295. // worksheet name, cell reference and cell value.
  296. func (f *File) SetCellBool(sheet, cell string, value bool) error {
  297. ws, err := f.workSheetReader(sheet)
  298. if err != nil {
  299. return err
  300. }
  301. c, col, row, err := f.prepareCell(ws, cell)
  302. if err != nil {
  303. return err
  304. }
  305. ws.Lock()
  306. defer ws.Unlock()
  307. c.S = f.prepareCellStyle(ws, col, row, c.S)
  308. c.T, c.V = setCellBool(value)
  309. c.IS = nil
  310. return f.removeFormula(c, ws, sheet)
  311. }
  312. // setCellBool prepares cell type and string type cell value by a given
  313. // boolean value.
  314. func setCellBool(value bool) (t string, v string) {
  315. t = "b"
  316. if value {
  317. v = "1"
  318. } else {
  319. v = "0"
  320. }
  321. return
  322. }
  323. // SetCellFloat sets a floating point value into a cell. The precision
  324. // parameter specifies how many places after the decimal will be shown
  325. // while -1 is a special value that will use as many decimal places as
  326. // necessary to represent the number. bitSize is 32 or 64 depending on if a
  327. // float32 or float64 was originally used for the value. For Example:
  328. //
  329. // var x float32 = 1.325
  330. // f.SetCellFloat("Sheet1", "A1", float64(x), 2, 32)
  331. func (f *File) SetCellFloat(sheet, cell string, value float64, precision, bitSize int) error {
  332. ws, err := f.workSheetReader(sheet)
  333. if err != nil {
  334. return err
  335. }
  336. c, col, row, err := f.prepareCell(ws, cell)
  337. if err != nil {
  338. return err
  339. }
  340. ws.Lock()
  341. defer ws.Unlock()
  342. c.S = f.prepareCellStyle(ws, col, row, c.S)
  343. c.T, c.V = setCellFloat(value, precision, bitSize)
  344. c.IS = nil
  345. return f.removeFormula(c, ws, sheet)
  346. }
  347. // setCellFloat prepares cell type and string type cell value by a given
  348. // float value.
  349. func setCellFloat(value float64, precision, bitSize int) (t string, v string) {
  350. v = strconv.FormatFloat(value, 'f', precision, bitSize)
  351. return
  352. }
  353. // SetCellStr provides a function to set string type value of a cell. Total
  354. // number of characters that a cell can contain 32767 characters.
  355. func (f *File) SetCellStr(sheet, cell, value string) error {
  356. ws, err := f.workSheetReader(sheet)
  357. if err != nil {
  358. return err
  359. }
  360. c, col, row, err := f.prepareCell(ws, cell)
  361. if err != nil {
  362. return err
  363. }
  364. ws.Lock()
  365. defer ws.Unlock()
  366. c.S = f.prepareCellStyle(ws, col, row, c.S)
  367. if c.T, c.V, err = f.setCellString(value); err != nil {
  368. return err
  369. }
  370. c.IS = nil
  371. return f.removeFormula(c, ws, sheet)
  372. }
  373. // setCellString provides a function to set string type to shared string
  374. // table.
  375. func (f *File) setCellString(value string) (t, v string, err error) {
  376. if len(value) > TotalCellChars {
  377. value = value[:TotalCellChars]
  378. }
  379. t = "s"
  380. var si int
  381. if si, err = f.setSharedString(value); err != nil {
  382. return
  383. }
  384. v = strconv.Itoa(si)
  385. return
  386. }
  387. // sharedStringsLoader load shared string table from system temporary file to
  388. // memory, and reset shared string table for reader.
  389. func (f *File) sharedStringsLoader() (err error) {
  390. f.Lock()
  391. defer f.Unlock()
  392. if path, ok := f.tempFiles.Load(defaultXMLPathSharedStrings); ok {
  393. f.Pkg.Store(defaultXMLPathSharedStrings, f.readBytes(defaultXMLPathSharedStrings))
  394. f.tempFiles.Delete(defaultXMLPathSharedStrings)
  395. if err = os.Remove(path.(string)); err != nil {
  396. return
  397. }
  398. f.SharedStrings = nil
  399. }
  400. if f.sharedStringTemp != nil {
  401. if err := f.sharedStringTemp.Close(); err != nil {
  402. return err
  403. }
  404. f.tempFiles.Delete(defaultTempFileSST)
  405. f.sharedStringItem, err = nil, os.Remove(f.sharedStringTemp.Name())
  406. f.sharedStringTemp = nil
  407. }
  408. return
  409. }
  410. // setSharedString provides a function to add string to the share string table.
  411. func (f *File) setSharedString(val string) (int, error) {
  412. if err := f.sharedStringsLoader(); err != nil {
  413. return 0, err
  414. }
  415. sst, err := f.sharedStringsReader()
  416. if err != nil {
  417. return 0, err
  418. }
  419. f.Lock()
  420. defer f.Unlock()
  421. if i, ok := f.sharedStringsMap[val]; ok {
  422. return i, nil
  423. }
  424. sst.Count++
  425. sst.UniqueCount++
  426. t := xlsxT{Val: val}
  427. val, t.Space = trimCellValue(val)
  428. sst.SI = append(sst.SI, xlsxSI{T: &t})
  429. f.sharedStringsMap[val] = sst.UniqueCount - 1
  430. return sst.UniqueCount - 1, nil
  431. }
  432. // trimCellValue provides a function to set string type to cell.
  433. func trimCellValue(value string) (v string, ns xml.Attr) {
  434. if len(value) > TotalCellChars {
  435. value = value[:TotalCellChars]
  436. }
  437. if len(value) > 0 {
  438. prefix, suffix := value[0], value[len(value)-1]
  439. for _, ascii := range []byte{9, 10, 13, 32} {
  440. if prefix == ascii || suffix == ascii {
  441. ns = xml.Attr{
  442. Name: xml.Name{Space: NameSpaceXML, Local: "space"},
  443. Value: "preserve",
  444. }
  445. break
  446. }
  447. }
  448. }
  449. v = bstrMarshal(value)
  450. return
  451. }
  452. // setCellValue set cell data type and value for (inline) rich string cell or
  453. // formula cell.
  454. func (c *xlsxC) setCellValue(val string) {
  455. if c.F != nil {
  456. c.setStr(val)
  457. return
  458. }
  459. c.setInlineStr(val)
  460. }
  461. // setInlineStr set cell data type and value which containing an (inline) rich
  462. // string.
  463. func (c *xlsxC) setInlineStr(val string) {
  464. c.T, c.V, c.IS = "inlineStr", "", &xlsxSI{T: &xlsxT{}}
  465. buf := &bytes.Buffer{}
  466. _ = xml.EscapeText(buf, []byte(val))
  467. c.IS.T.Val, c.IS.T.Space = trimCellValue(buf.String())
  468. }
  469. // setStr set cell data type and value which containing a formula string.
  470. func (c *xlsxC) setStr(val string) {
  471. c.T, c.IS = "str", nil
  472. c.V, c.XMLSpace = trimCellValue(val)
  473. }
  474. // getCellDate parse cell value which containing a boolean.
  475. func (c *xlsxC) getCellBool(f *File, raw bool) (string, error) {
  476. if !raw {
  477. if c.V == "1" {
  478. return "TRUE", nil
  479. }
  480. if c.V == "0" {
  481. return "FALSE", nil
  482. }
  483. }
  484. return f.formattedValue(c.S, c.V, raw)
  485. }
  486. // setCellDefault prepares cell type and string type cell value by a given
  487. // string.
  488. func (c *xlsxC) setCellDefault(value string) {
  489. if ok, _, _ := isNumeric(value); !ok {
  490. if value != "" {
  491. c.setInlineStr(value)
  492. c.IS.T.Val = value
  493. return
  494. }
  495. c.T, c.V, c.IS = value, value, nil
  496. return
  497. }
  498. c.T, c.V = "", value
  499. }
  500. // getCellDate parse cell value which contains a date in the ISO 8601 format.
  501. func (c *xlsxC) getCellDate(f *File, raw bool) (string, error) {
  502. if !raw {
  503. layout := "20060102T150405.999"
  504. if strings.HasSuffix(c.V, "Z") {
  505. layout = "20060102T150405Z"
  506. if strings.Contains(c.V, "-") {
  507. layout = "2006-01-02T15:04:05Z"
  508. }
  509. } else if strings.Contains(c.V, "-") {
  510. layout = "2006-01-02 15:04:05Z"
  511. }
  512. if timestamp, err := time.Parse(layout, strings.ReplaceAll(c.V, ",", ".")); err == nil {
  513. excelTime, _ := timeToExcelTime(timestamp, false)
  514. c.V = strconv.FormatFloat(excelTime, 'G', 15, 64)
  515. }
  516. }
  517. return f.formattedValue(c.S, c.V, raw)
  518. }
  519. // getValueFrom return a value from a column/row cell, this function is
  520. // intended to be used with for range on rows an argument with the spreadsheet
  521. // opened file.
  522. func (c *xlsxC) getValueFrom(f *File, d *xlsxSST, raw bool) (string, error) {
  523. f.Lock()
  524. defer f.Unlock()
  525. switch c.T {
  526. case "b":
  527. return c.getCellBool(f, raw)
  528. case "d":
  529. return c.getCellDate(f, raw)
  530. case "s":
  531. if c.V != "" {
  532. xlsxSI := 0
  533. xlsxSI, _ = strconv.Atoi(strings.TrimSpace(c.V))
  534. if _, ok := f.tempFiles.Load(defaultXMLPathSharedStrings); ok {
  535. return f.formattedValue(c.S, f.getFromStringItem(xlsxSI), raw)
  536. }
  537. if len(d.SI) > xlsxSI {
  538. return f.formattedValue(c.S, d.SI[xlsxSI].String(), raw)
  539. }
  540. }
  541. return f.formattedValue(c.S, c.V, raw)
  542. case "inlineStr":
  543. if c.IS != nil {
  544. return f.formattedValue(c.S, c.IS.String(), raw)
  545. }
  546. return f.formattedValue(c.S, c.V, raw)
  547. default:
  548. if isNum, precision, decimal := isNumeric(c.V); isNum && !raw {
  549. if precision > 15 {
  550. c.V = strconv.FormatFloat(decimal, 'G', 15, 64)
  551. } else {
  552. c.V = strconv.FormatFloat(decimal, 'f', -1, 64)
  553. }
  554. }
  555. return f.formattedValue(c.S, c.V, raw)
  556. }
  557. }
  558. // SetCellDefault provides a function to set string type value of a cell as
  559. // default format without escaping the cell.
  560. func (f *File) SetCellDefault(sheet, cell, value string) error {
  561. ws, err := f.workSheetReader(sheet)
  562. if err != nil {
  563. return err
  564. }
  565. c, col, row, err := f.prepareCell(ws, cell)
  566. if err != nil {
  567. return err
  568. }
  569. ws.Lock()
  570. defer ws.Unlock()
  571. c.S = f.prepareCellStyle(ws, col, row, c.S)
  572. c.setCellDefault(value)
  573. return f.removeFormula(c, ws, sheet)
  574. }
  575. // GetCellFormula provides a function to get formula from cell by given
  576. // worksheet name and cell reference in spreadsheet.
  577. func (f *File) GetCellFormula(sheet, cell string) (string, error) {
  578. return f.getCellStringFunc(sheet, cell, func(x *xlsxWorksheet, c *xlsxC) (string, bool, error) {
  579. if c.F == nil {
  580. return "", false, nil
  581. }
  582. if c.F.T == STCellFormulaTypeShared && c.F.Si != nil {
  583. return getSharedFormula(x, *c.F.Si, c.R), true, nil
  584. }
  585. return c.F.Content, true, nil
  586. })
  587. }
  588. // FormulaOpts can be passed to SetCellFormula to use other formula types.
  589. type FormulaOpts struct {
  590. Type *string // Formula type
  591. Ref *string // Shared formula ref
  592. }
  593. // SetCellFormula provides a function to set formula on the cell is taken
  594. // according to the given worksheet name and cell formula settings. The result
  595. // of the formula cell can be calculated when the worksheet is opened by the
  596. // Office Excel application or can be using the "CalcCellValue" function also
  597. // can get the calculated cell value. If the Excel application doesn't
  598. // calculate the formula automatically when the workbook has been opened,
  599. // please call "UpdateLinkedValue" after setting the cell formula functions.
  600. //
  601. // Example 1, set normal formula "=SUM(A1,B1)" for the cell "A3" on "Sheet1":
  602. //
  603. // err := f.SetCellFormula("Sheet1", "A3", "=SUM(A1,B1)")
  604. //
  605. // Example 2, set one-dimensional vertical constant array (column array) formula
  606. // "1,2,3" for the cell "A3" on "Sheet1":
  607. //
  608. // err := f.SetCellFormula("Sheet1", "A3", "={1;2;3}")
  609. //
  610. // Example 3, set one-dimensional horizontal constant array (row array)
  611. // formula '"a","b","c"' for the cell "A3" on "Sheet1":
  612. //
  613. // err := f.SetCellFormula("Sheet1", "A3", "={\"a\",\"b\",\"c\"}")
  614. //
  615. // Example 4, set two-dimensional constant array formula '{1,2,"a","b"}' for
  616. // the cell "A3" on "Sheet1":
  617. //
  618. // formulaType, ref := excelize.STCellFormulaTypeArray, "A3:A3"
  619. // err := f.SetCellFormula("Sheet1", "A3", "={1,2;\"a\",\"b\"}",
  620. // excelize.FormulaOpts{Ref: &ref, Type: &formulaType})
  621. //
  622. // Example 5, set range array formula "A1:A2" for the cell "A3" on "Sheet1":
  623. //
  624. // formulaType, ref := excelize.STCellFormulaTypeArray, "A3:A3"
  625. // err := f.SetCellFormula("Sheet1", "A3", "=A1:A2",
  626. // excelize.FormulaOpts{Ref: &ref, Type: &formulaType})
  627. //
  628. // Example 6, set shared formula "=A1+B1" for the cell "C1:C5"
  629. // on "Sheet1", "C1" is the master cell:
  630. //
  631. // formulaType, ref := excelize.STCellFormulaTypeShared, "C1:C5"
  632. // err := f.SetCellFormula("Sheet1", "C1", "=A1+B1",
  633. // excelize.FormulaOpts{Ref: &ref, Type: &formulaType})
  634. //
  635. // Example 7, set table formula "=SUM(Table1[[A]:[B]])" for the cell "C2"
  636. // on "Sheet1":
  637. //
  638. // package main
  639. //
  640. // import (
  641. // "fmt"
  642. //
  643. // "github.com/xuri/excelize/v2"
  644. // )
  645. //
  646. // func main() {
  647. // f := excelize.NewFile()
  648. // defer func() {
  649. // if err := f.Close(); err != nil {
  650. // fmt.Println(err)
  651. // }
  652. // }()
  653. // for idx, row := range [][]interface{}{{"A", "B", "C"}, {1, 2}} {
  654. // if err := f.SetSheetRow("Sheet1", fmt.Sprintf("A%d", idx+1), &row); err != nil {
  655. // fmt.Println(err)
  656. // return
  657. // }
  658. // }
  659. // if err := f.AddTable("Sheet1", &excelize.Table{
  660. // Range: "A1:C2", Name: "Table1", StyleName: "TableStyleMedium2",
  661. // }); err != nil {
  662. // fmt.Println(err)
  663. // return
  664. // }
  665. // formulaType := excelize.STCellFormulaTypeDataTable
  666. // if err := f.SetCellFormula("Sheet1", "C2", "=SUM(Table1[[A]:[B]])",
  667. // excelize.FormulaOpts{Type: &formulaType}); err != nil {
  668. // fmt.Println(err)
  669. // return
  670. // }
  671. // if err := f.SaveAs("Book1.xlsx"); err != nil {
  672. // fmt.Println(err)
  673. // }
  674. // }
  675. func (f *File) SetCellFormula(sheet, cell, formula string, opts ...FormulaOpts) error {
  676. ws, err := f.workSheetReader(sheet)
  677. if err != nil {
  678. return err
  679. }
  680. c, _, _, err := f.prepareCell(ws, cell)
  681. if err != nil {
  682. return err
  683. }
  684. if formula == "" {
  685. c.F = nil
  686. return f.deleteCalcChain(f.getSheetID(sheet), cell)
  687. }
  688. if c.F != nil {
  689. c.F.Content = formula
  690. } else {
  691. c.F = &xlsxF{Content: formula}
  692. }
  693. for _, opt := range opts {
  694. if opt.Type != nil {
  695. if *opt.Type == STCellFormulaTypeDataTable {
  696. return err
  697. }
  698. c.F.T = *opt.Type
  699. if c.F.T == STCellFormulaTypeShared {
  700. if err = ws.setSharedFormula(*opt.Ref); err != nil {
  701. return err
  702. }
  703. }
  704. }
  705. if opt.Ref != nil {
  706. c.F.Ref = *opt.Ref
  707. }
  708. }
  709. c.T, c.IS = "str", nil
  710. return err
  711. }
  712. // setSharedFormula set shared formula for the cells.
  713. func (ws *xlsxWorksheet) setSharedFormula(ref string) error {
  714. coordinates, err := rangeRefToCoordinates(ref)
  715. if err != nil {
  716. return err
  717. }
  718. _ = sortCoordinates(coordinates)
  719. cnt := ws.countSharedFormula()
  720. for c := coordinates[0]; c <= coordinates[2]; c++ {
  721. for r := coordinates[1]; r <= coordinates[3]; r++ {
  722. prepareSheetXML(ws, c, r)
  723. cell := &ws.SheetData.Row[r-1].C[c-1]
  724. if cell.F == nil {
  725. cell.F = &xlsxF{}
  726. }
  727. cell.F.T = STCellFormulaTypeShared
  728. cell.F.Si = &cnt
  729. }
  730. }
  731. return err
  732. }
  733. // countSharedFormula count shared formula in the given worksheet.
  734. func (ws *xlsxWorksheet) countSharedFormula() (count int) {
  735. for _, row := range ws.SheetData.Row {
  736. for _, cell := range row.C {
  737. if cell.F != nil && cell.F.Si != nil && *cell.F.Si+1 > count {
  738. count = *cell.F.Si + 1
  739. }
  740. }
  741. }
  742. return
  743. }
  744. // GetCellHyperLink gets a cell hyperlink based on the given worksheet name and
  745. // cell reference. If the cell has a hyperlink, it will return 'true' and
  746. // the link address, otherwise it will return 'false' and an empty link
  747. // address.
  748. //
  749. // For example, get a hyperlink to a 'H6' cell on a worksheet named 'Sheet1':
  750. //
  751. // link, target, err := f.GetCellHyperLink("Sheet1", "H6")
  752. func (f *File) GetCellHyperLink(sheet, cell string) (bool, string, error) {
  753. // Check for correct cell name
  754. if _, _, err := SplitCellName(cell); err != nil {
  755. return false, "", err
  756. }
  757. ws, err := f.workSheetReader(sheet)
  758. if err != nil {
  759. return false, "", err
  760. }
  761. if ws.Hyperlinks != nil {
  762. for _, link := range ws.Hyperlinks.Hyperlink {
  763. ok, err := f.checkCellInRangeRef(cell, link.Ref)
  764. if err != nil {
  765. return false, "", err
  766. }
  767. if link.Ref == cell || ok {
  768. if link.RID != "" {
  769. return true, f.getSheetRelationshipsTargetByID(sheet, link.RID), err
  770. }
  771. return true, link.Location, err
  772. }
  773. }
  774. }
  775. return false, "", err
  776. }
  777. // HyperlinkOpts can be passed to SetCellHyperlink to set optional hyperlink
  778. // attributes (e.g. display value)
  779. type HyperlinkOpts struct {
  780. Display *string
  781. Tooltip *string
  782. }
  783. // SetCellHyperLink provides a function to set cell hyperlink by given
  784. // worksheet name and link URL address. LinkType defines two types of
  785. // hyperlink "External" for website or "Location" for moving to one of cell in
  786. // this workbook. Maximum limit hyperlinks in a worksheet is 65530. This
  787. // function is only used to set the hyperlink of the cell and doesn't affect
  788. // the value of the cell. If you need to set the value of the cell, please use
  789. // the other functions such as `SetCellStyle` or `SetSheetRow`. The below is
  790. // example for external link.
  791. //
  792. // display, tooltip := "https://github.com/xuri/excelize", "Excelize on GitHub"
  793. // if err := f.SetCellHyperLink("Sheet1", "A3",
  794. // display, "External", excelize.HyperlinkOpts{
  795. // Display: &display,
  796. // Tooltip: &tooltip,
  797. // }); err != nil {
  798. // fmt.Println(err)
  799. // }
  800. // // Set underline and font color style for the cell.
  801. // style, err := f.NewStyle(&excelize.Style{
  802. // Font: &excelize.Font{Color: "1265BE", Underline: "single"},
  803. // })
  804. // if err != nil {
  805. // fmt.Println(err)
  806. // }
  807. // err = f.SetCellStyle("Sheet1", "A3", "A3", style)
  808. //
  809. // This is another example for "Location":
  810. //
  811. // err := f.SetCellHyperLink("Sheet1", "A3", "Sheet1!A40", "Location")
  812. func (f *File) SetCellHyperLink(sheet, cell, link, linkType string, opts ...HyperlinkOpts) error {
  813. // Check for correct cell name
  814. if _, _, err := SplitCellName(cell); err != nil {
  815. return err
  816. }
  817. ws, err := f.workSheetReader(sheet)
  818. if err != nil {
  819. return err
  820. }
  821. if cell, err = f.mergeCellsParser(ws, cell); err != nil {
  822. return err
  823. }
  824. var linkData xlsxHyperlink
  825. idx := -1
  826. if ws.Hyperlinks == nil {
  827. ws.Hyperlinks = new(xlsxHyperlinks)
  828. }
  829. for i, hyperlink := range ws.Hyperlinks.Hyperlink {
  830. if hyperlink.Ref == cell {
  831. idx = i
  832. linkData = hyperlink
  833. break
  834. }
  835. }
  836. if len(ws.Hyperlinks.Hyperlink) > TotalSheetHyperlinks {
  837. return ErrTotalSheetHyperlinks
  838. }
  839. switch linkType {
  840. case "External":
  841. sheetPath, _ := f.getSheetXMLPath(sheet)
  842. sheetRels := "xl/worksheets/_rels/" + strings.TrimPrefix(sheetPath, "xl/worksheets/") + ".rels"
  843. rID := f.setRels(linkData.RID, sheetRels, SourceRelationshipHyperLink, link, linkType)
  844. linkData = xlsxHyperlink{
  845. Ref: cell,
  846. }
  847. linkData.RID = "rId" + strconv.Itoa(rID)
  848. f.addSheetNameSpace(sheet, SourceRelationship)
  849. case "Location":
  850. linkData = xlsxHyperlink{
  851. Ref: cell,
  852. Location: link,
  853. }
  854. default:
  855. return fmt.Errorf("invalid link type %q", linkType)
  856. }
  857. for _, o := range opts {
  858. if o.Display != nil {
  859. linkData.Display = *o.Display
  860. }
  861. if o.Tooltip != nil {
  862. linkData.Tooltip = *o.Tooltip
  863. }
  864. }
  865. if idx == -1 {
  866. ws.Hyperlinks.Hyperlink = append(ws.Hyperlinks.Hyperlink, linkData)
  867. return err
  868. }
  869. ws.Hyperlinks.Hyperlink[idx] = linkData
  870. return err
  871. }
  872. // getCellRichText returns rich text of cell by given string item.
  873. func getCellRichText(si *xlsxSI) (runs []RichTextRun) {
  874. for _, v := range si.R {
  875. run := RichTextRun{
  876. Text: v.T.Val,
  877. }
  878. if v.RPr != nil {
  879. run.Font = newFont(v.RPr)
  880. }
  881. runs = append(runs, run)
  882. }
  883. return
  884. }
  885. // GetCellRichText provides a function to get rich text of cell by given
  886. // worksheet.
  887. func (f *File) GetCellRichText(sheet, cell string) (runs []RichTextRun, err error) {
  888. ws, err := f.workSheetReader(sheet)
  889. if err != nil {
  890. return
  891. }
  892. c, _, _, err := f.prepareCell(ws, cell)
  893. if err != nil {
  894. return
  895. }
  896. siIdx, err := strconv.Atoi(c.V)
  897. if err != nil || c.T != "s" {
  898. return
  899. }
  900. sst, err := f.sharedStringsReader()
  901. if err != nil {
  902. return
  903. }
  904. if len(sst.SI) <= siIdx || siIdx < 0 {
  905. return
  906. }
  907. runs = getCellRichText(&sst.SI[siIdx])
  908. return
  909. }
  910. // newRpr create run properties for the rich text by given font format.
  911. func newRpr(fnt *Font) *xlsxRPr {
  912. rpr := xlsxRPr{}
  913. trueVal := ""
  914. if fnt.Bold {
  915. rpr.B = &trueVal
  916. }
  917. if fnt.Italic {
  918. rpr.I = &trueVal
  919. }
  920. if fnt.Strike {
  921. rpr.Strike = &trueVal
  922. }
  923. if fnt.Underline != "" {
  924. rpr.U = &attrValString{Val: &fnt.Underline}
  925. }
  926. if fnt.Family != "" {
  927. rpr.RFont = &attrValString{Val: &fnt.Family}
  928. }
  929. if inStrSlice([]string{"baseline", "superscript", "subscript"}, fnt.VertAlign, true) != -1 {
  930. rpr.VertAlign = &attrValString{Val: &fnt.VertAlign}
  931. }
  932. if fnt.Size > 0 {
  933. rpr.Sz = &attrValFloat{Val: &fnt.Size}
  934. }
  935. rpr.Color = newFontColor(fnt)
  936. return &rpr
  937. }
  938. // newFont create font format by given run properties for the rich text.
  939. func newFont(rPr *xlsxRPr) *Font {
  940. font := Font{Underline: "none"}
  941. font.Bold = rPr.B != nil
  942. font.Italic = rPr.I != nil
  943. if rPr.U != nil {
  944. font.Underline = "single"
  945. if rPr.U.Val != nil {
  946. font.Underline = *rPr.U.Val
  947. }
  948. }
  949. if rPr.RFont != nil && rPr.RFont.Val != nil {
  950. font.Family = *rPr.RFont.Val
  951. }
  952. if rPr.Sz != nil && rPr.Sz.Val != nil {
  953. font.Size = *rPr.Sz.Val
  954. }
  955. font.Strike = rPr.Strike != nil
  956. if rPr.Color != nil {
  957. font.Color = strings.TrimPrefix(rPr.Color.RGB, "FF")
  958. if rPr.Color.Theme != nil {
  959. font.ColorTheme = rPr.Color.Theme
  960. }
  961. font.ColorIndexed = rPr.Color.Indexed
  962. font.ColorTint = rPr.Color.Tint
  963. }
  964. return &font
  965. }
  966. // setRichText provides a function to set rich text of a cell.
  967. func setRichText(runs []RichTextRun) ([]xlsxR, error) {
  968. var (
  969. textRuns []xlsxR
  970. totalCellChars int
  971. )
  972. for _, textRun := range runs {
  973. totalCellChars += len(textRun.Text)
  974. if totalCellChars > TotalCellChars {
  975. return textRuns, ErrCellCharsLength
  976. }
  977. run := xlsxR{T: &xlsxT{}}
  978. run.T.Val, run.T.Space = trimCellValue(textRun.Text)
  979. fnt := textRun.Font
  980. if fnt != nil {
  981. run.RPr = newRpr(fnt)
  982. }
  983. textRuns = append(textRuns, run)
  984. }
  985. return textRuns, nil
  986. }
  987. // SetCellRichText provides a function to set cell with rich text by given
  988. // worksheet. For example, set rich text on the A1 cell of the worksheet named
  989. // Sheet1:
  990. //
  991. // package main
  992. //
  993. // import (
  994. // "fmt"
  995. //
  996. // "github.com/xuri/excelize/v2"
  997. // )
  998. //
  999. // func main() {
  1000. // f := excelize.NewFile()
  1001. // defer func() {
  1002. // if err := f.Close(); err != nil {
  1003. // fmt.Println(err)
  1004. // }
  1005. // }()
  1006. // if err := f.SetRowHeight("Sheet1", 1, 35); err != nil {
  1007. // fmt.Println(err)
  1008. // return
  1009. // }
  1010. // if err := f.SetColWidth("Sheet1", "A", "A", 44); err != nil {
  1011. // fmt.Println(err)
  1012. // return
  1013. // }
  1014. // if err := f.SetCellRichText("Sheet1", "A1", []excelize.RichTextRun{
  1015. // {
  1016. // Text: "bold",
  1017. // Font: &excelize.Font{
  1018. // Bold: true,
  1019. // Color: "2354e8",
  1020. // Family: "Times New Roman",
  1021. // },
  1022. // },
  1023. // {
  1024. // Text: " and ",
  1025. // Font: &excelize.Font{
  1026. // Family: "Times New Roman",
  1027. // },
  1028. // },
  1029. // {
  1030. // Text: "italic ",
  1031. // Font: &excelize.Font{
  1032. // Bold: true,
  1033. // Color: "e83723",
  1034. // Italic: true,
  1035. // Family: "Times New Roman",
  1036. // },
  1037. // },
  1038. // {
  1039. // Text: "text with color and font-family,",
  1040. // Font: &excelize.Font{
  1041. // Bold: true,
  1042. // Color: "2354e8",
  1043. // Family: "Times New Roman",
  1044. // },
  1045. // },
  1046. // {
  1047. // Text: "\r\nlarge text with ",
  1048. // Font: &excelize.Font{
  1049. // Size: 14,
  1050. // Color: "ad23e8",
  1051. // },
  1052. // },
  1053. // {
  1054. // Text: "strike",
  1055. // Font: &excelize.Font{
  1056. // Color: "e89923",
  1057. // Strike: true,
  1058. // },
  1059. // },
  1060. // {
  1061. // Text: " superscript",
  1062. // Font: &excelize.Font{
  1063. // Color: "dbc21f",
  1064. // VertAlign: "superscript",
  1065. // },
  1066. // },
  1067. // {
  1068. // Text: " and ",
  1069. // Font: &excelize.Font{
  1070. // Size: 14,
  1071. // Color: "ad23e8",
  1072. // VertAlign: "baseline",
  1073. // },
  1074. // },
  1075. // {
  1076. // Text: "underline",
  1077. // Font: &excelize.Font{
  1078. // Color: "23e833",
  1079. // Underline: "single",
  1080. // },
  1081. // },
  1082. // {
  1083. // Text: " subscript.",
  1084. // Font: &excelize.Font{
  1085. // Color: "017505",
  1086. // VertAlign: "subscript",
  1087. // },
  1088. // },
  1089. // }); err != nil {
  1090. // fmt.Println(err)
  1091. // return
  1092. // }
  1093. // style, err := f.NewStyle(&excelize.Style{
  1094. // Alignment: &excelize.Alignment{
  1095. // WrapText: true,
  1096. // },
  1097. // })
  1098. // if err != nil {
  1099. // fmt.Println(err)
  1100. // return
  1101. // }
  1102. // if err := f.SetCellStyle("Sheet1", "A1", "A1", style); err != nil {
  1103. // fmt.Println(err)
  1104. // return
  1105. // }
  1106. // if err := f.SaveAs("Book1.xlsx"); err != nil {
  1107. // fmt.Println(err)
  1108. // }
  1109. // }
  1110. func (f *File) SetCellRichText(sheet, cell string, runs []RichTextRun) error {
  1111. ws, err := f.workSheetReader(sheet)
  1112. if err != nil {
  1113. return err
  1114. }
  1115. c, col, row, err := f.prepareCell(ws, cell)
  1116. if err != nil {
  1117. return err
  1118. }
  1119. if err := f.sharedStringsLoader(); err != nil {
  1120. return err
  1121. }
  1122. c.S = f.prepareCellStyle(ws, col, row, c.S)
  1123. si := xlsxSI{}
  1124. sst, err := f.sharedStringsReader()
  1125. if err != nil {
  1126. return err
  1127. }
  1128. if si.R, err = setRichText(runs); err != nil {
  1129. return err
  1130. }
  1131. for idx, strItem := range sst.SI {
  1132. if reflect.DeepEqual(strItem, si) {
  1133. c.T, c.V = "s", strconv.Itoa(idx)
  1134. return err
  1135. }
  1136. }
  1137. sst.SI = append(sst.SI, si)
  1138. sst.Count++
  1139. sst.UniqueCount++
  1140. c.T, c.V = "s", strconv.Itoa(len(sst.SI)-1)
  1141. return err
  1142. }
  1143. // SetSheetRow writes an array to row by given worksheet name, starting
  1144. // cell reference and a pointer to array type 'slice'. This function is
  1145. // concurrency safe. For example, writes an array to row 6 start with the cell
  1146. // B6 on Sheet1:
  1147. //
  1148. // err := f.SetSheetRow("Sheet1", "B6", &[]interface{}{"1", nil, 2})
  1149. func (f *File) SetSheetRow(sheet, cell string, slice interface{}) error {
  1150. return f.setSheetCells(sheet, cell, slice, rows)
  1151. }
  1152. // SetSheetCol writes an array to column by given worksheet name, starting
  1153. // cell reference and a pointer to array type 'slice'. For example, writes an
  1154. // array to column B start with the cell B6 on Sheet1:
  1155. //
  1156. // err := f.SetSheetCol("Sheet1", "B6", &[]interface{}{"1", nil, 2})
  1157. func (f *File) SetSheetCol(sheet, cell string, slice interface{}) error {
  1158. return f.setSheetCells(sheet, cell, slice, columns)
  1159. }
  1160. // setSheetCells provides a function to set worksheet cells value.
  1161. func (f *File) setSheetCells(sheet, cell string, slice interface{}, dir adjustDirection) error {
  1162. col, row, err := CellNameToCoordinates(cell)
  1163. if err != nil {
  1164. return err
  1165. }
  1166. // Make sure 'slice' is a Ptr to Slice
  1167. v := reflect.ValueOf(slice)
  1168. if v.Kind() != reflect.Ptr || v.Elem().Kind() != reflect.Slice {
  1169. return ErrParameterInvalid
  1170. }
  1171. v = v.Elem()
  1172. for i := 0; i < v.Len(); i++ {
  1173. var cell string
  1174. var err error
  1175. if dir == rows {
  1176. cell, err = CoordinatesToCellName(col+i, row)
  1177. } else {
  1178. cell, err = CoordinatesToCellName(col, row+i)
  1179. }
  1180. // Error should never happen here. But keep checking to early detect regressions
  1181. // if it will be introduced in the future.
  1182. if err != nil {
  1183. return err
  1184. }
  1185. if err := f.SetCellValue(sheet, cell, v.Index(i).Interface()); err != nil {
  1186. return err
  1187. }
  1188. }
  1189. return err
  1190. }
  1191. // getCellInfo does common preparation for all set cell value functions.
  1192. func (f *File) prepareCell(ws *xlsxWorksheet, cell string) (*xlsxC, int, int, error) {
  1193. var err error
  1194. cell, err = f.mergeCellsParser(ws, cell)
  1195. if err != nil {
  1196. return nil, 0, 0, err
  1197. }
  1198. col, row, err := CellNameToCoordinates(cell)
  1199. if err != nil {
  1200. return nil, 0, 0, err
  1201. }
  1202. prepareSheetXML(ws, col, row)
  1203. ws.Lock()
  1204. defer ws.Unlock()
  1205. return &ws.SheetData.Row[row-1].C[col-1], col, row, err
  1206. }
  1207. // getCellStringFunc does common value extraction workflow for all get cell
  1208. // value function. Passed function implements specific part of required
  1209. // logic.
  1210. func (f *File) getCellStringFunc(sheet, cell string, fn func(x *xlsxWorksheet, c *xlsxC) (string, bool, error)) (string, error) {
  1211. ws, err := f.workSheetReader(sheet)
  1212. if err != nil {
  1213. return "", err
  1214. }
  1215. cell, err = f.mergeCellsParser(ws, cell)
  1216. if err != nil {
  1217. return "", err
  1218. }
  1219. _, row, err := CellNameToCoordinates(cell)
  1220. if err != nil {
  1221. return "", err
  1222. }
  1223. ws.Lock()
  1224. defer ws.Unlock()
  1225. lastRowNum := 0
  1226. if l := len(ws.SheetData.Row); l > 0 {
  1227. lastRowNum = ws.SheetData.Row[l-1].R
  1228. }
  1229. // keep in mind: row starts from 1
  1230. if row > lastRowNum {
  1231. return "", nil
  1232. }
  1233. for rowIdx := range ws.SheetData.Row {
  1234. rowData := &ws.SheetData.Row[rowIdx]
  1235. if rowData.R != row {
  1236. continue
  1237. }
  1238. for colIdx := range rowData.C {
  1239. colData := &rowData.C[colIdx]
  1240. if cell != colData.R {
  1241. continue
  1242. }
  1243. val, ok, err := fn(ws, colData)
  1244. if err != nil {
  1245. return "", err
  1246. }
  1247. if ok {
  1248. return val, nil
  1249. }
  1250. }
  1251. }
  1252. return "", nil
  1253. }
  1254. // formattedValue provides a function to returns a value after formatted. If
  1255. // it is possible to apply a format to the cell value, it will do so, if not
  1256. // then an error will be returned, along with the raw value of the cell.
  1257. func (f *File) formattedValue(s int, v string, raw bool) (string, error) {
  1258. if raw {
  1259. return v, nil
  1260. }
  1261. if s == 0 {
  1262. return v, nil
  1263. }
  1264. styleSheet, err := f.stylesReader()
  1265. if err != nil {
  1266. return v, err
  1267. }
  1268. if styleSheet.CellXfs == nil {
  1269. return v, err
  1270. }
  1271. if s >= len(styleSheet.CellXfs.Xf) || s < 0 {
  1272. return v, err
  1273. }
  1274. var numFmtID int
  1275. if styleSheet.CellXfs.Xf[s].NumFmtID != nil {
  1276. numFmtID = *styleSheet.CellXfs.Xf[s].NumFmtID
  1277. }
  1278. date1904 := false
  1279. wb, err := f.workbookReader()
  1280. if err != nil {
  1281. return v, err
  1282. }
  1283. if wb != nil && wb.WorkbookPr != nil {
  1284. date1904 = wb.WorkbookPr.Date1904
  1285. }
  1286. if ok := builtInNumFmtFunc[numFmtID]; ok != nil {
  1287. return ok(v, builtInNumFmt[numFmtID], date1904), err
  1288. }
  1289. if styleSheet.NumFmts == nil {
  1290. return v, err
  1291. }
  1292. for _, xlsxFmt := range styleSheet.NumFmts.NumFmt {
  1293. if xlsxFmt.NumFmtID == numFmtID {
  1294. return format(v, xlsxFmt.FormatCode, date1904), err
  1295. }
  1296. }
  1297. return v, err
  1298. }
  1299. // prepareCellStyle provides a function to prepare style index of cell in
  1300. // worksheet by given column index and style index.
  1301. func (f *File) prepareCellStyle(ws *xlsxWorksheet, col, row, style int) int {
  1302. if style != 0 {
  1303. return style
  1304. }
  1305. if row <= len(ws.SheetData.Row) {
  1306. if styleID := ws.SheetData.Row[row-1].S; styleID != 0 {
  1307. return styleID
  1308. }
  1309. }
  1310. if ws.Cols != nil {
  1311. for _, c := range ws.Cols.Col {
  1312. if c.Min <= col && col <= c.Max && c.Style != 0 {
  1313. return c.Style
  1314. }
  1315. }
  1316. }
  1317. return style
  1318. }
  1319. // mergeCellsParser provides a function to check merged cells in worksheet by
  1320. // given cell reference.
  1321. func (f *File) mergeCellsParser(ws *xlsxWorksheet, cell string) (string, error) {
  1322. cell = strings.ToUpper(cell)
  1323. col, row, err := CellNameToCoordinates(cell)
  1324. if err != nil {
  1325. return cell, err
  1326. }
  1327. if ws.MergeCells != nil {
  1328. for i := 0; i < len(ws.MergeCells.Cells); i++ {
  1329. if ws.MergeCells.Cells[i] == nil {
  1330. ws.MergeCells.Cells = append(ws.MergeCells.Cells[:i], ws.MergeCells.Cells[i+1:]...)
  1331. i--
  1332. continue
  1333. }
  1334. if ref := ws.MergeCells.Cells[i].Ref; len(ws.MergeCells.Cells[i].rect) == 0 && ref != "" {
  1335. if strings.Count(ref, ":") != 1 {
  1336. ref += ":" + ref
  1337. }
  1338. rect, err := rangeRefToCoordinates(ref)
  1339. if err != nil {
  1340. return cell, err
  1341. }
  1342. _ = sortCoordinates(rect)
  1343. ws.MergeCells.Cells[i].rect = rect
  1344. }
  1345. if cellInRange([]int{col, row}, ws.MergeCells.Cells[i].rect) {
  1346. cell = strings.Split(ws.MergeCells.Cells[i].Ref, ":")[0]
  1347. break
  1348. }
  1349. }
  1350. }
  1351. return cell, nil
  1352. }
  1353. // checkCellInRangeRef provides a function to determine if a given cell reference
  1354. // in a range.
  1355. func (f *File) checkCellInRangeRef(cell, rangeRef string) (bool, error) {
  1356. col, row, err := CellNameToCoordinates(cell)
  1357. if err != nil {
  1358. return false, err
  1359. }
  1360. if rng := strings.Split(rangeRef, ":"); len(rng) != 2 {
  1361. return false, err
  1362. }
  1363. coordinates, err := rangeRefToCoordinates(rangeRef)
  1364. if err != nil {
  1365. return false, err
  1366. }
  1367. return cellInRange([]int{col, row}, coordinates), err
  1368. }
  1369. // cellInRange provides a function to determine if a given range is within a
  1370. // range.
  1371. func cellInRange(cell, ref []int) bool {
  1372. return cell[0] >= ref[0] && cell[0] <= ref[2] && cell[1] >= ref[1] && cell[1] <= ref[3]
  1373. }
  1374. // isOverlap find if the given two rectangles overlap or not.
  1375. func isOverlap(rect1, rect2 []int) bool {
  1376. return cellInRange([]int{rect1[0], rect1[1]}, rect2) ||
  1377. cellInRange([]int{rect1[2], rect1[1]}, rect2) ||
  1378. cellInRange([]int{rect1[0], rect1[3]}, rect2) ||
  1379. cellInRange([]int{rect1[2], rect1[3]}, rect2) ||
  1380. cellInRange([]int{rect2[0], rect2[1]}, rect1) ||
  1381. cellInRange([]int{rect2[2], rect2[1]}, rect1) ||
  1382. cellInRange([]int{rect2[0], rect2[3]}, rect1) ||
  1383. cellInRange([]int{rect2[2], rect2[3]}, rect1)
  1384. }
  1385. // parseSharedFormula generate dynamic part of shared formula for target cell
  1386. // by given column and rows distance and origin shared formula.
  1387. func parseSharedFormula(dCol, dRow int, orig []byte) (res string, start int) {
  1388. var (
  1389. end int
  1390. stringLiteral bool
  1391. )
  1392. for end = 0; end < len(orig); end++ {
  1393. c := orig[end]
  1394. if c == '"' {
  1395. stringLiteral = !stringLiteral
  1396. }
  1397. if stringLiteral {
  1398. continue // Skip characters in quotes
  1399. }
  1400. if c >= 'A' && c <= 'Z' || c == '$' {
  1401. res += string(orig[start:end])
  1402. start = end
  1403. end++
  1404. foundNum := false
  1405. for ; end < len(orig); end++ {
  1406. idc := orig[end]
  1407. if idc >= '0' && idc <= '9' || idc == '$' {
  1408. foundNum = true
  1409. } else if idc >= 'A' && idc <= 'Z' {
  1410. if foundNum {
  1411. break
  1412. }
  1413. } else {
  1414. break
  1415. }
  1416. }
  1417. if foundNum {
  1418. cellID := string(orig[start:end])
  1419. res += shiftCell(cellID, dCol, dRow)
  1420. start = end
  1421. }
  1422. }
  1423. }
  1424. return
  1425. }
  1426. // getSharedFormula find a cell contains the same formula as another cell,
  1427. // the "shared" value can be used for the t attribute and the si attribute can
  1428. // be used to refer to the cell containing the formula. Two formulas are
  1429. // considered to be the same when their respective representations in
  1430. // R1C1-reference notation, are the same.
  1431. //
  1432. // Note that this function not validate ref tag to check the cell whether in
  1433. // allow range reference, and always return origin shared formula.
  1434. func getSharedFormula(ws *xlsxWorksheet, si int, cell string) string {
  1435. for _, r := range ws.SheetData.Row {
  1436. for _, c := range r.C {
  1437. if c.F != nil && c.F.Ref != "" && c.F.T == STCellFormulaTypeShared && c.F.Si != nil && *c.F.Si == si {
  1438. col, row, _ := CellNameToCoordinates(cell)
  1439. sharedCol, sharedRow, _ := CellNameToCoordinates(c.R)
  1440. dCol := col - sharedCol
  1441. dRow := row - sharedRow
  1442. orig := []byte(c.F.Content)
  1443. res, start := parseSharedFormula(dCol, dRow, orig)
  1444. if start < len(orig) {
  1445. res += string(orig[start:])
  1446. }
  1447. return res
  1448. }
  1449. }
  1450. }
  1451. return ""
  1452. }
  1453. // shiftCell returns the cell shifted according to dCol and dRow taking into
  1454. // consideration absolute references with dollar sign ($)
  1455. func shiftCell(cellID string, dCol, dRow int) string {
  1456. fCol, fRow, _ := CellNameToCoordinates(cellID)
  1457. signCol, signRow := "", ""
  1458. if strings.Index(cellID, "$") == 0 {
  1459. signCol = "$"
  1460. } else {
  1461. // Shift column
  1462. fCol += dCol
  1463. }
  1464. if strings.LastIndex(cellID, "$") > 0 {
  1465. signRow = "$"
  1466. } else {
  1467. // Shift row
  1468. fRow += dRow
  1469. }
  1470. colName, _ := ColumnNumberToName(fCol)
  1471. return signCol + colName + signRow + strconv.Itoa(fRow)
  1472. }