cell.go 11 KB

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