cell.go 12 KB

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