cell.go 9.6 KB

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