cell.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. package xlsx
  2. import (
  3. "fmt"
  4. "math"
  5. "strconv"
  6. "time"
  7. )
  8. const (
  9. maxNonScientificNumber = 1e11
  10. minNonScientificNumber = 1e-9
  11. )
  12. // CellType is an int type for storing metadata about the data type in the cell.
  13. type CellType int
  14. // These are the cell types from the ST_CellType spec
  15. const (
  16. CellTypeString CellType = iota
  17. // CellTypeStringFormula is a specific format for formulas that return string values. Formulas that return numbers
  18. // and booleans are stored as those types.
  19. CellTypeStringFormula
  20. CellTypeNumeric
  21. CellTypeBool
  22. // CellTypeInline is not respected on save, all inline string cells will be saved as SharedStrings
  23. // when saving to an XLSX file. This the same behavior as that found in Excel.
  24. CellTypeInline
  25. CellTypeError
  26. // d (Date): Cell contains a date in the ISO 8601 format.
  27. // That is the only mention of this format in the XLSX spec.
  28. // Date seems to be unused by the current version of Excel, it stores dates as Numeric cells with a date format string.
  29. // For now these cells will have their value output directly. It is unclear if the value is supposed to be parsed
  30. // into a number and then formatted using the formatting or not.
  31. CellTypeDate
  32. )
  33. func (ct CellType) Ptr() *CellType {
  34. return &ct
  35. }
  36. // Cell is a high level structure intended to provide user access to
  37. // the contents of Cell within an xlsx.Row.
  38. type Cell struct {
  39. Row *Row
  40. Value string
  41. formula string
  42. style *Style
  43. NumFmt string
  44. parsedNumFmt *parsedNumberFormat
  45. date1904 bool
  46. Hidden bool
  47. HMerge int
  48. VMerge int
  49. cellType CellType
  50. }
  51. // CellInterface defines the public API of the Cell.
  52. type CellInterface interface {
  53. String() string
  54. FormattedValue() string
  55. }
  56. // NewCell creates a cell and adds it to a row.
  57. func NewCell(r *Row) *Cell {
  58. return &Cell{Row: r, NumFmt: "general"}
  59. }
  60. // Merge with other cells, horizontally and/or vertically.
  61. func (c *Cell) Merge(hcells, vcells int) {
  62. c.HMerge = hcells
  63. c.VMerge = vcells
  64. }
  65. // Type returns the CellType of a cell. See CellType constants for more details.
  66. func (c *Cell) Type() CellType {
  67. return c.cellType
  68. }
  69. // SetString sets the value of a cell to a string.
  70. func (c *Cell) SetString(s string) {
  71. c.Value = s
  72. c.formula = ""
  73. c.cellType = CellTypeString
  74. }
  75. // String returns the value of a Cell as a string. If you'd like to
  76. // see errors returned from formatting then please use
  77. // Cell.FormattedValue() instead.
  78. func (c *Cell) String() string {
  79. // To preserve the String() interface we'll throw away errors.
  80. // Not that using FormattedValue is therefore strongly
  81. // preferred.
  82. value, _ := c.FormattedValue()
  83. return value
  84. }
  85. // SetFloat sets the value of a cell to a float.
  86. func (c *Cell) SetFloat(n float64) {
  87. c.SetValue(n)
  88. }
  89. //GetTime returns the value of a Cell as a time.Time
  90. func (c *Cell) GetTime(date1904 bool) (t time.Time, err error) {
  91. f, err := c.Float()
  92. if err != nil {
  93. return t, err
  94. }
  95. return TimeFromExcelTime(f, date1904), nil
  96. }
  97. /*
  98. The following are samples of format samples.
  99. * "0.00e+00"
  100. * "0", "#,##0"
  101. * "0.00", "#,##0.00", "@"
  102. * "#,##0 ;(#,##0)", "#,##0 ;[red](#,##0)"
  103. * "#,##0.00;(#,##0.00)", "#,##0.00;[red](#,##0.00)"
  104. * "0%", "0.00%"
  105. * "0.00e+00", "##0.0e+0"
  106. */
  107. // SetFloatWithFormat sets the value of a cell to a float and applies
  108. // formatting to the cell.
  109. func (c *Cell) SetFloatWithFormat(n float64, format string) {
  110. c.SetValue(n)
  111. c.NumFmt = format
  112. c.formula = ""
  113. }
  114. // DateTimeOptions are additional options for exporting times
  115. type DateTimeOptions struct {
  116. // Location allows calculating times in other timezones/locations
  117. Location *time.Location
  118. // ExcelTimeFormat is the string you want excel to use to format the datetime
  119. ExcelTimeFormat string
  120. }
  121. var (
  122. DefaultDateFormat = builtInNumFmt[14]
  123. DefaultDateTimeFormat = builtInNumFmt[22]
  124. DefaultDateOptions = DateTimeOptions{
  125. Location: timeLocationUTC,
  126. ExcelTimeFormat: DefaultDateFormat,
  127. }
  128. DefaultDateTimeOptions = DateTimeOptions{
  129. Location: timeLocationUTC,
  130. ExcelTimeFormat: DefaultDateTimeFormat,
  131. }
  132. )
  133. // SetDate sets the value of a cell to a float.
  134. func (c *Cell) SetDate(t time.Time) {
  135. c.SetDateWithOptions(t, DefaultDateOptions)
  136. }
  137. func (c *Cell) SetDateTime(t time.Time) {
  138. c.SetDateWithOptions(t, DefaultDateTimeOptions)
  139. }
  140. // SetDateWithOptions allows for more granular control when exporting dates and times
  141. func (c *Cell) SetDateWithOptions(t time.Time, options DateTimeOptions) {
  142. _, offset := t.In(options.Location).Zone()
  143. t = time.Unix(t.Unix()+int64(offset), 0)
  144. c.SetDateTimeWithFormat(TimeToExcelTime(t.In(timeLocationUTC), c.date1904), options.ExcelTimeFormat)
  145. }
  146. func (c *Cell) SetDateTimeWithFormat(n float64, format string) {
  147. c.Value = strconv.FormatFloat(n, 'f', -1, 64)
  148. c.NumFmt = format
  149. c.formula = ""
  150. c.cellType = CellTypeNumeric
  151. }
  152. // Float returns the value of cell as a number.
  153. func (c *Cell) Float() (float64, error) {
  154. f, err := strconv.ParseFloat(c.Value, 64)
  155. if err != nil {
  156. return math.NaN(), err
  157. }
  158. return f, nil
  159. }
  160. // SetInt64 sets a cell's value to a 64-bit integer.
  161. func (c *Cell) SetInt64(n int64) {
  162. c.SetValue(n)
  163. }
  164. // Int64 returns the value of cell as 64-bit integer.
  165. func (c *Cell) Int64() (int64, error) {
  166. f, err := strconv.ParseInt(c.Value, 10, 64)
  167. if err != nil {
  168. return -1, err
  169. }
  170. return f, nil
  171. }
  172. // GeneralNumeric returns the value of the cell as a string. It is formatted very closely to the the XLSX spec for how
  173. // to display values when the storage type is Number and the format type is General. It is not 100% identical to the
  174. // spec but is as close as you can get using the built in Go formatting tools.
  175. func (c *Cell) GeneralNumeric() (string, error) {
  176. return generalNumericScientific(c.Value, true)
  177. }
  178. // GeneralNumericWithoutScientific returns numbers that are always formatted as numbers, but it does not follow
  179. // the rules for when XLSX should switch to scientific notation, since sometimes scientific notation is not desired,
  180. // even if that is how the document is supposed to be formatted.
  181. func (c *Cell) GeneralNumericWithoutScientific() (string, error) {
  182. return generalNumericScientific(c.Value, false)
  183. }
  184. // SetInt sets a cell's value to an integer.
  185. func (c *Cell) SetInt(n int) {
  186. c.SetValue(n)
  187. }
  188. // SetInt sets a cell's value to an integer.
  189. func (c *Cell) SetValue(n interface{}) {
  190. switch t := n.(type) {
  191. case time.Time:
  192. c.SetDateTime(t)
  193. return
  194. case int, int8, int16, int32, int64:
  195. c.setNumeric(fmt.Sprintf("%d", n))
  196. case float64:
  197. // When formatting floats, do not use fmt.Sprintf("%v", n), this will cause numbers below 1e-4 to be printed in
  198. // scientific notation. Scientific notation is not a valid way to store numbers in XML.
  199. // Also not not use fmt.Sprintf("%f", n), this will cause numbers to be stored as X.XXXXXX. Which means that
  200. // numbers will lose precision and numbers with fewer significant digits such as 0 will be stored as 0.000000
  201. // which causes tests to fail.
  202. c.setNumeric(strconv.FormatFloat(t, 'f', -1, 64))
  203. case float32:
  204. c.setNumeric(strconv.FormatFloat(float64(t), 'f', -1, 32))
  205. case string:
  206. c.SetString(t)
  207. case []byte:
  208. c.SetString(string(t))
  209. case nil:
  210. c.SetString("")
  211. default:
  212. c.SetString(fmt.Sprintf("%v", n))
  213. }
  214. }
  215. // setNumeric sets a cell's value to a number
  216. func (c *Cell) setNumeric(s string) {
  217. c.Value = s
  218. c.NumFmt = builtInNumFmt[builtInNumFmtIndex_GENERAL]
  219. c.formula = ""
  220. c.cellType = CellTypeNumeric
  221. }
  222. // Int returns the value of cell as integer.
  223. // Has max 53 bits of precision
  224. // See: float64(int64(math.MaxInt))
  225. func (c *Cell) Int() (int, error) {
  226. f, err := strconv.ParseFloat(c.Value, 64)
  227. if err != nil {
  228. return -1, err
  229. }
  230. return int(f), nil
  231. }
  232. // SetBool sets a cell's value to a boolean.
  233. func (c *Cell) SetBool(b bool) {
  234. if b {
  235. c.Value = "1"
  236. } else {
  237. c.Value = "0"
  238. }
  239. c.cellType = CellTypeBool
  240. }
  241. // Bool returns a boolean from a cell's value.
  242. // TODO: Determine if the current return value is
  243. // appropriate for types other than CellTypeBool.
  244. func (c *Cell) Bool() bool {
  245. // If bool, just return the value.
  246. if c.cellType == CellTypeBool {
  247. return c.Value == "1"
  248. }
  249. // If numeric, base it on a non-zero.
  250. if c.cellType == CellTypeNumeric {
  251. return c.Value != "0"
  252. }
  253. // Return whether there's an empty string.
  254. return c.Value != ""
  255. }
  256. // SetFormula sets the format string for a cell.
  257. func (c *Cell) SetFormula(formula string) {
  258. c.formula = formula
  259. c.cellType = CellTypeNumeric
  260. }
  261. func (c *Cell) SetStringFormula(formula string) {
  262. c.formula = formula
  263. c.cellType = CellTypeStringFormula
  264. }
  265. // Formula returns the formula string for the cell.
  266. func (c *Cell) Formula() string {
  267. return c.formula
  268. }
  269. // GetStyle returns the Style associated with a Cell
  270. func (c *Cell) GetStyle() *Style {
  271. if c.style == nil {
  272. c.style = NewStyle()
  273. }
  274. return c.style
  275. }
  276. // SetStyle sets the style of a cell.
  277. func (c *Cell) SetStyle(style *Style) {
  278. c.style = style
  279. }
  280. // GetNumberFormat returns the number format string for a cell.
  281. func (c *Cell) GetNumberFormat() string {
  282. return c.NumFmt
  283. }
  284. func (c *Cell) formatToFloat(format string) (string, error) {
  285. f, err := strconv.ParseFloat(c.Value, 64)
  286. if err != nil {
  287. return c.Value, err
  288. }
  289. return fmt.Sprintf(format, f), nil
  290. }
  291. func (c *Cell) formatToInt(format string) (string, error) {
  292. f, err := strconv.ParseFloat(c.Value, 64)
  293. if err != nil {
  294. return c.Value, err
  295. }
  296. return fmt.Sprintf(format, int(f)), nil
  297. }
  298. // getNumberFormat will update the parsedNumFmt struct if it has become out of date, since a cell's NumFmt string is a
  299. // public field that could be edited by clients.
  300. func (c *Cell) getNumberFormat() *parsedNumberFormat {
  301. if c.parsedNumFmt == nil || c.parsedNumFmt.numFmt != c.NumFmt {
  302. c.parsedNumFmt = parseFullNumberFormatString(c.NumFmt)
  303. }
  304. return c.parsedNumFmt
  305. }
  306. // FormattedValue returns a value, and possibly an error condition
  307. // from a Cell. If it is possible to apply a format to the cell
  308. // value, it will do so, if not then an error will be returned, along
  309. // with the raw value of the Cell.
  310. func (c *Cell) FormattedValue() (string, error) {
  311. fullFormat := c.getNumberFormat()
  312. returnVal, err := fullFormat.FormatValue(c)
  313. if fullFormat.parseEncounteredError != nil {
  314. return returnVal, *fullFormat.parseEncounteredError
  315. }
  316. return returnVal, err
  317. }