cell.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. package xlsx
  2. import (
  3. "fmt"
  4. "math"
  5. "strconv"
  6. "strings"
  7. "time"
  8. )
  9. const (
  10. maxNonScientificNumber = 1e11
  11. minNonScientificNumber = 1e-9
  12. )
  13. // CellType is an int type for storing metadata about the data type in the cell.
  14. type CellType int
  15. // Known types for cell values.
  16. const (
  17. CellTypeString CellType = iota
  18. CellTypeFormula
  19. CellTypeNumeric
  20. CellTypeBool
  21. CellTypeInline
  22. CellTypeError
  23. CellTypeDate
  24. CellTypeGeneral
  25. )
  26. func (ct CellType) Ptr() *CellType {
  27. return &ct
  28. }
  29. // Cell is a high level structure intended to provide user access to
  30. // the contents of Cell within an xlsx.Row.
  31. type Cell struct {
  32. Row *Row
  33. Value string
  34. formula string
  35. style *Style
  36. NumFmt string
  37. date1904 bool
  38. Hidden bool
  39. HMerge int
  40. VMerge int
  41. cellType CellType
  42. }
  43. // CellInterface defines the public API of the Cell.
  44. type CellInterface interface {
  45. String() string
  46. FormattedValue() string
  47. }
  48. // NewCell creates a cell and adds it to a row.
  49. func NewCell(r *Row) *Cell {
  50. return &Cell{Row: r}
  51. }
  52. // Merge with other cells, horizontally and/or vertically.
  53. func (c *Cell) Merge(hcells, vcells int) {
  54. c.HMerge = hcells
  55. c.VMerge = vcells
  56. }
  57. // Type returns the CellType of a cell. See CellType constants for more details.
  58. func (c *Cell) Type() CellType {
  59. return c.cellType
  60. }
  61. // SetString sets the value of a cell to a string.
  62. func (c *Cell) SetString(s string) {
  63. c.Value = s
  64. c.formula = ""
  65. c.cellType = CellTypeString
  66. }
  67. // String returns the value of a Cell as a string. If you'd like to
  68. // see errors returned from formatting then please use
  69. // Cell.FormattedValue() instead.
  70. func (c *Cell) String() string {
  71. // To preserve the String() interface we'll throw away errors.
  72. // Not that using FormattedValue is therefore strongly
  73. // preferred.
  74. value, _ := c.FormattedValue()
  75. return value
  76. }
  77. // SetFloat sets the value of a cell to a float.
  78. func (c *Cell) SetFloat(n float64) {
  79. c.SetValue(n)
  80. }
  81. //GetTime returns the value of a Cell as a time.Time
  82. func (c *Cell) GetTime(date1904 bool) (t time.Time, err error) {
  83. f, err := c.Float()
  84. if err != nil {
  85. return t, err
  86. }
  87. return TimeFromExcelTime(f, date1904), nil
  88. }
  89. /*
  90. The following are samples of format samples.
  91. * "0.00e+00"
  92. * "0", "#,##0"
  93. * "0.00", "#,##0.00", "@"
  94. * "#,##0 ;(#,##0)", "#,##0 ;[red](#,##0)"
  95. * "#,##0.00;(#,##0.00)", "#,##0.00;[red](#,##0.00)"
  96. * "0%", "0.00%"
  97. * "0.00e+00", "##0.0e+0"
  98. */
  99. // SetFloatWithFormat sets the value of a cell to a float and applies
  100. // formatting to the cell.
  101. func (c *Cell) SetFloatWithFormat(n float64, format string) {
  102. // beauty the output when the float is small enough
  103. if n != 0 && n < 0.00001 {
  104. c.Value = strconv.FormatFloat(n, 'e', -1, 64)
  105. } else {
  106. c.Value = strconv.FormatFloat(n, 'f', -1, 64)
  107. }
  108. c.NumFmt = format
  109. c.formula = ""
  110. c.cellType = CellTypeNumeric
  111. }
  112. var timeLocationUTC, _ = time.LoadLocation("UTC")
  113. func TimeToUTCTime(t time.Time) time.Time {
  114. return time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), timeLocationUTC)
  115. }
  116. func TimeToExcelTime(t time.Time) float64 {
  117. return float64(t.UnixNano())/8.64e13 + 25569.0
  118. }
  119. // DateTimeOptions are additional options for exporting times
  120. type DateTimeOptions struct {
  121. // Location allows calculating times in other timezones/locations
  122. Location *time.Location
  123. // ExcelTimeFormat is the string you want excel to use to format the datetime
  124. ExcelTimeFormat string
  125. }
  126. var (
  127. DefaultDateFormat = builtInNumFmt[14]
  128. DefaultDateTimeFormat = builtInNumFmt[22]
  129. DefaultDateOptions = DateTimeOptions{
  130. Location: timeLocationUTC,
  131. ExcelTimeFormat: DefaultDateFormat,
  132. }
  133. DefaultDateTimeOptions = DateTimeOptions{
  134. Location: timeLocationUTC,
  135. ExcelTimeFormat: DefaultDateTimeFormat,
  136. }
  137. )
  138. // SetDate sets the value of a cell to a float.
  139. func (c *Cell) SetDate(t time.Time) {
  140. c.SetDateWithOptions(t, DefaultDateOptions)
  141. }
  142. func (c *Cell) SetDateTime(t time.Time) {
  143. c.SetDateWithOptions(t, DefaultDateTimeOptions)
  144. }
  145. // SetDateWithOptions allows for more granular control when exporting dates and times
  146. func (c *Cell) SetDateWithOptions(t time.Time, options DateTimeOptions) {
  147. _, offset := t.In(options.Location).Zone()
  148. t = time.Unix(t.Unix()+int64(offset), 0)
  149. c.SetDateTimeWithFormat(TimeToExcelTime(t.In(timeLocationUTC)), options.ExcelTimeFormat)
  150. }
  151. func (c *Cell) SetDateTimeWithFormat(n float64, format string) {
  152. c.Value = strconv.FormatFloat(n, 'f', -1, 64)
  153. c.NumFmt = format
  154. c.formula = ""
  155. c.cellType = CellTypeDate
  156. }
  157. // Float returns the value of cell as a number.
  158. func (c *Cell) Float() (float64, error) {
  159. f, err := strconv.ParseFloat(c.Value, 64)
  160. if err != nil {
  161. return math.NaN(), err
  162. }
  163. return f, nil
  164. }
  165. // SetInt64 sets a cell's value to a 64-bit integer.
  166. func (c *Cell) SetInt64(n int64) {
  167. c.SetValue(n)
  168. }
  169. // Int64 returns the value of cell as 64-bit integer.
  170. func (c *Cell) Int64() (int64, error) {
  171. f, err := strconv.ParseInt(c.Value, 10, 64)
  172. if err != nil {
  173. return -1, err
  174. }
  175. return f, nil
  176. }
  177. // SetInt sets a cell's value to an integer.
  178. func (c *Cell) SetInt(n int) {
  179. c.SetValue(n)
  180. }
  181. // SetInt sets a cell's value to an integer.
  182. func (c *Cell) SetValue(n interface{}) {
  183. switch t := n.(type) {
  184. case time.Time:
  185. c.SetDateTime(n.(time.Time))
  186. return
  187. case int, int8, int16, int32, int64, float32, float64:
  188. c.setGeneral(fmt.Sprintf("%v", n))
  189. case string:
  190. c.SetString(t)
  191. case []byte:
  192. c.SetString(string(t))
  193. case nil:
  194. c.SetString("")
  195. default:
  196. c.SetString(fmt.Sprintf("%v", n))
  197. }
  198. }
  199. // SetInt sets a cell's value to an integer.
  200. func (c *Cell) setGeneral(s string) {
  201. c.Value = s
  202. c.NumFmt = builtInNumFmt[builtInNumFmtIndex_GENERAL]
  203. c.formula = ""
  204. c.cellType = CellTypeGeneral
  205. }
  206. // Int returns the value of cell as integer.
  207. // Has max 53 bits of precision
  208. // See: float64(int64(math.MaxInt))
  209. func (c *Cell) Int() (int, error) {
  210. f, err := strconv.ParseFloat(c.Value, 64)
  211. if err != nil {
  212. return -1, err
  213. }
  214. return int(f), nil
  215. }
  216. // SetBool sets a cell's value to a boolean.
  217. func (c *Cell) SetBool(b bool) {
  218. if b {
  219. c.Value = "1"
  220. } else {
  221. c.Value = "0"
  222. }
  223. c.cellType = CellTypeBool
  224. }
  225. // Bool returns a boolean from a cell's value.
  226. // TODO: Determine if the current return value is
  227. // appropriate for types other than CellTypeBool.
  228. func (c *Cell) Bool() bool {
  229. // If bool, just return the value.
  230. if c.cellType == CellTypeBool {
  231. return c.Value == "1"
  232. }
  233. // If numeric, base it on a non-zero.
  234. if c.cellType == CellTypeNumeric || c.cellType == CellTypeGeneral {
  235. return c.Value != "0"
  236. }
  237. // Return whether there's an empty string.
  238. return c.Value != ""
  239. }
  240. // SetFormula sets the format string for a cell.
  241. func (c *Cell) SetFormula(formula string) {
  242. c.formula = formula
  243. c.cellType = CellTypeFormula
  244. }
  245. // Formula returns the formula string for the cell.
  246. func (c *Cell) Formula() string {
  247. return c.formula
  248. }
  249. // GetStyle returns the Style associated with a Cell
  250. func (c *Cell) GetStyle() *Style {
  251. if c.style == nil {
  252. c.style = NewStyle()
  253. }
  254. return c.style
  255. }
  256. // SetStyle sets the style of a cell.
  257. func (c *Cell) SetStyle(style *Style) {
  258. c.style = style
  259. }
  260. // GetNumberFormat returns the number format string for a cell.
  261. func (c *Cell) GetNumberFormat() string {
  262. return c.NumFmt
  263. }
  264. func (c *Cell) formatToFloat(format string) (string, error) {
  265. f, err := strconv.ParseFloat(c.Value, 64)
  266. if err != nil {
  267. return c.Value, err
  268. }
  269. return fmt.Sprintf(format, f), nil
  270. }
  271. func (c *Cell) formatToInt(format string) (string, error) {
  272. f, err := strconv.ParseFloat(c.Value, 64)
  273. if err != nil {
  274. return c.Value, err
  275. }
  276. return fmt.Sprintf(format, int(f)), nil
  277. }
  278. // FormattedValue returns a value, and possibly an error condition
  279. // from a Cell. If it is possible to apply a format to the cell
  280. // value, it will do so, if not then an error will be returned, along
  281. // with the raw value of the Cell.
  282. //
  283. // This is the documentation of the "General" Format in the Office Open XML spec:
  284. //
  285. // Numbers
  286. // The application shall attempt to display the full number up to 11 digits (inc. decimal point). If the number is too
  287. // large*, the application shall attempt to show exponential format. If the number has too many significant digits, the
  288. // display shall be truncated. The optimal method of display is based on the available cell width. If the number cannot
  289. // be displayed using any of these formats in the available width, the application shall show "#" across the width of
  290. // the cell.
  291. //
  292. // Conditions for switching to exponential format:
  293. // 1. The cell value shall have at least five digits for xE-xx
  294. // 2. If the exponent is bigger than the size allowed, a floating point number cannot fit, so try exponential notation.
  295. // 3. Similarly, for negative exponents, check if there is space for even one (non-zero) digit in floating point format**.
  296. // 4. Finally, if there isn't room for all of the significant digits in floating point format (for a negative exponent),
  297. // exponential format shall display more digits if the exponent is less than -3. (The 3 is because E-xx takes 4
  298. // characters, and the leading 0 in floating point takes only 1 character. Thus, for an exponent less than -3, there is
  299. // more than 3 additional leading 0's, more than enough to compensate for the size of the E-xx.)
  300. //
  301. // Floating point rule:
  302. // For general formatting in cells, max overall length for cell display is 11, not including negative sign, but includes
  303. // leading zeros and decimal separator.***
  304. //
  305. // Added Notes:
  306. // * "If the number is too large" means "if the number has more than 11 digits", so greater than or equal to 1e11.
  307. // ** Means that you should switch to scientific if there would be 9 zeros after the decimal (the decimal and first zero
  308. // count against the 11 character limit), so less than 1e9.
  309. // *** The way this is written, you can get numbers that are more than 11 characters because the golang Float fmt
  310. // does not support adjusting the precision while not padding with zeros, while also not switching to scientific
  311. // notation too early.
  312. func (c *Cell) FormattedValue() (string, error) {
  313. var numberFormat = c.GetNumberFormat()
  314. if isTimeFormat(numberFormat) {
  315. return parseTime(c)
  316. }
  317. switch numberFormat {
  318. case builtInNumFmt[builtInNumFmtIndex_GENERAL]:
  319. if c.cellType == CellTypeNumeric {
  320. // If the cell type is Numeric, format the string the way it should be shown to the user.
  321. f, err := strconv.ParseFloat(c.Value, 64)
  322. if err != nil {
  323. return c.Value, err
  324. }
  325. // When using General format, numbers that are less than 1e-9 (0.000000001) and greater than or equal to
  326. // 1e11 (100,000,000,000) should be shown in scientific notation.
  327. if f < minNonScientificNumber || f >= maxNonScientificNumber {
  328. return strconv.FormatFloat(f, 'E', -1, 64), nil
  329. }
  330. // This format (fmt="f", prec=-1) will prevent padding with zeros and will never switch to scientific notation.
  331. // However, it will show more than 11 characters for very precise numbers, and this cannot be changed.
  332. // You could also use fmt="g", prec=11, which doesn't pad with zeros and allows the correct precision,
  333. // but it will use scientific notation on numbers less than 1e-4. That value is hardcoded and cannot be
  334. // configured or disabled.
  335. return strconv.FormatFloat(f, 'f', -1, 64), nil
  336. }
  337. return c.Value, nil
  338. case builtInNumFmt[builtInNumFmtIndex_STRING]:
  339. return c.Value, nil
  340. case builtInNumFmt[builtInNumFmtIndex_INT], "#,##0":
  341. return c.formatToInt("%d")
  342. case builtInNumFmt[builtInNumFmtIndex_FLOAT], "#,##0.00":
  343. return c.formatToFloat("%.2f")
  344. case "#,##0 ;(#,##0)", "#,##0 ;[red](#,##0)":
  345. f, err := strconv.ParseFloat(c.Value, 64)
  346. if err != nil {
  347. return c.Value, err
  348. }
  349. if f < 0 {
  350. i := int(math.Abs(f))
  351. return fmt.Sprintf("(%d)", i), nil
  352. }
  353. i := int(f)
  354. return fmt.Sprintf("%d", i), nil
  355. case "#,##0.00;(#,##0.00)", "#,##0.00;[red](#,##0.00)":
  356. f, err := strconv.ParseFloat(c.Value, 64)
  357. if err != nil {
  358. return c.Value, err
  359. }
  360. if f < 0 {
  361. return fmt.Sprintf("(%.2f)", f), nil
  362. }
  363. return fmt.Sprintf("%.2f", f), nil
  364. case "0%":
  365. f, err := strconv.ParseFloat(c.Value, 64)
  366. if err != nil {
  367. return c.Value, err
  368. }
  369. f = f * 100
  370. return fmt.Sprintf("%d%%", int(f)), nil
  371. case "0.00%":
  372. f, err := strconv.ParseFloat(c.Value, 64)
  373. if err != nil {
  374. return c.Value, err
  375. }
  376. f = f * 100
  377. return fmt.Sprintf("%.2f%%", f), nil
  378. case "0.00e+00", "##0.0e+0":
  379. return c.formatToFloat("%e")
  380. }
  381. return c.Value, nil
  382. }
  383. // parseTime returns a string parsed using time.Time
  384. func parseTime(c *Cell) (string, error) {
  385. f, err := strconv.ParseFloat(c.Value, 64)
  386. if err != nil {
  387. return c.Value, err
  388. }
  389. val := TimeFromExcelTime(f, c.date1904)
  390. format := c.GetNumberFormat()
  391. // Replace Excel placeholders with Go time placeholders.
  392. // For example, replace yyyy with 2006. These are in a specific order,
  393. // due to the fact that m is used in month, minute, and am/pm. It would
  394. // be easier to fix that with regular expressions, but if it's possible
  395. // to keep this simple it would be easier to maintain.
  396. // Full-length month and days (e.g. March, Tuesday) have letters in them that would be replaced
  397. // by other characters below (such as the 'h' in March, or the 'd' in Tuesday) below.
  398. // First we convert them to arbitrary characters unused in Excel Date formats, and then at the end,
  399. // turn them to what they should actually be.
  400. // Based off: http://www.ozgrid.com/Excel/CustomFormats.htm
  401. replacements := []struct{ xltime, gotime string }{
  402. {"yyyy", "2006"},
  403. {"yy", "06"},
  404. {"mmmm", "%%%%"},
  405. {"dddd", "&&&&"},
  406. {"dd", "02"},
  407. {"d", "2"},
  408. {"mmm", "Jan"},
  409. {"mmss", "0405"},
  410. {"ss", "05"},
  411. {"mm:", "04:"},
  412. {":mm", ":04"},
  413. {"mm", "01"},
  414. {"am/pm", "pm"},
  415. {"m/", "1/"},
  416. {"%%%%", "January"},
  417. {"&&&&", "Monday"},
  418. }
  419. // It is the presence of the "am/pm" indicator that determins
  420. // if this is a 12 hour or 24 hours time format, not the
  421. // number of 'h' characters.
  422. if is12HourTime(format) {
  423. format = strings.Replace(format, "hh", "03", 1)
  424. format = strings.Replace(format, "h", "3", 1)
  425. } else {
  426. format = strings.Replace(format, "hh", "15", 1)
  427. format = strings.Replace(format, "h", "15", 1)
  428. }
  429. for _, repl := range replacements {
  430. format = strings.Replace(format, repl.xltime, repl.gotime, 1)
  431. }
  432. // If the hour is optional, strip it out, along with the
  433. // possible dangling colon that would remain.
  434. if val.Hour() < 1 {
  435. format = strings.Replace(format, "]:", "]", 1)
  436. format = strings.Replace(format, "[03]", "", 1)
  437. format = strings.Replace(format, "[3]", "", 1)
  438. format = strings.Replace(format, "[15]", "", 1)
  439. } else {
  440. format = strings.Replace(format, "[3]", "3", 1)
  441. format = strings.Replace(format, "[15]", "15", 1)
  442. }
  443. return val.Format(format), nil
  444. }
  445. // isTimeFormat checks whether an Excel format string represents
  446. // a time.Time.
  447. func isTimeFormat(format string) bool {
  448. dateParts := []string{
  449. "yy", "hh", "h", "am/pm", "AM/PM", "A/P", "a/p", "ss", "mm", ":",
  450. }
  451. for _, part := range dateParts {
  452. if strings.Contains(format, part) {
  453. return true
  454. }
  455. }
  456. return false
  457. }
  458. // is12HourTime checks whether an Excel time format string is a 12
  459. // hours form.
  460. func is12HourTime(format string) bool {
  461. return strings.Contains(format, "am/pm") || strings.Contains(format, "AM/PM") || strings.Contains(format, "a/p") || strings.Contains(format, "A/P")
  462. }