cell.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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. DataValidation *xlsxCellDataValidation
  51. }
  52. // CellInterface defines the public API of the Cell.
  53. type CellInterface interface {
  54. String() string
  55. FormattedValue() string
  56. }
  57. // NewCell creates a cell and adds it to a row.
  58. func NewCell(r *Row) *Cell {
  59. return &Cell{Row: r}
  60. }
  61. // Merge with other cells, horizontally and/or vertically.
  62. func (c *Cell) Merge(hcells, vcells int) {
  63. c.HMerge = hcells
  64. c.VMerge = vcells
  65. }
  66. // Type returns the CellType of a cell. See CellType constants for more details.
  67. func (c *Cell) Type() CellType {
  68. return c.cellType
  69. }
  70. // SetString sets the value of a cell to a string.
  71. func (c *Cell) SetString(s string) {
  72. c.Value = s
  73. c.formula = ""
  74. c.cellType = CellTypeString
  75. }
  76. // String returns the value of a Cell as a string. If you'd like to
  77. // see errors returned from formatting then please use
  78. // Cell.FormattedValue() instead.
  79. func (c *Cell) String() string {
  80. // To preserve the String() interface we'll throw away errors.
  81. // Not that using FormattedValue is therefore strongly
  82. // preferred.
  83. value, _ := c.FormattedValue()
  84. return value
  85. }
  86. // SetFloat sets the value of a cell to a float.
  87. func (c *Cell) SetFloat(n float64) {
  88. c.SetValue(n)
  89. }
  90. //GetTime returns the value of a Cell as a time.Time
  91. func (c *Cell) GetTime(date1904 bool) (t time.Time, err error) {
  92. f, err := c.Float()
  93. if err != nil {
  94. return t, err
  95. }
  96. return TimeFromExcelTime(f, date1904), nil
  97. }
  98. /*
  99. The following are samples of format samples.
  100. * "0.00e+00"
  101. * "0", "#,##0"
  102. * "0.00", "#,##0.00", "@"
  103. * "#,##0 ;(#,##0)", "#,##0 ;[red](#,##0)"
  104. * "#,##0.00;(#,##0.00)", "#,##0.00;[red](#,##0.00)"
  105. * "0%", "0.00%"
  106. * "0.00e+00", "##0.0e+0"
  107. */
  108. // SetFloatWithFormat sets the value of a cell to a float and applies
  109. // formatting to the cell.
  110. func (c *Cell) SetFloatWithFormat(n float64, format string) {
  111. c.SetValue(n)
  112. c.NumFmt = format
  113. c.formula = ""
  114. }
  115. // SetCellFormat set cell value format
  116. func (c *Cell) SetFormat(format string) {
  117. c.NumFmt = format
  118. }
  119. var timeLocationUTC, _ = time.LoadLocation("UTC")
  120. func TimeToUTCTime(t time.Time) time.Time {
  121. return time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), timeLocationUTC)
  122. }
  123. func TimeToExcelTime(t time.Time) float64 {
  124. return float64(t.UnixNano())/8.64e13 + 25569.0
  125. }
  126. // DateTimeOptions are additional options for exporting times
  127. type DateTimeOptions struct {
  128. // Location allows calculating times in other timezones/locations
  129. Location *time.Location
  130. // ExcelTimeFormat is the string you want excel to use to format the datetime
  131. ExcelTimeFormat string
  132. }
  133. var (
  134. DefaultDateFormat = builtInNumFmt[14]
  135. DefaultDateTimeFormat = builtInNumFmt[22]
  136. DefaultDateOptions = DateTimeOptions{
  137. Location: timeLocationUTC,
  138. ExcelTimeFormat: DefaultDateFormat,
  139. }
  140. DefaultDateTimeOptions = DateTimeOptions{
  141. Location: timeLocationUTC,
  142. ExcelTimeFormat: DefaultDateTimeFormat,
  143. }
  144. )
  145. // SetDate sets the value of a cell to a float.
  146. func (c *Cell) SetDate(t time.Time) {
  147. c.SetDateWithOptions(t, DefaultDateOptions)
  148. }
  149. func (c *Cell) SetDateTime(t time.Time) {
  150. c.SetDateWithOptions(t, DefaultDateTimeOptions)
  151. }
  152. // SetDateWithOptions allows for more granular control when exporting dates and times
  153. func (c *Cell) SetDateWithOptions(t time.Time, options DateTimeOptions) {
  154. _, offset := t.In(options.Location).Zone()
  155. t = time.Unix(t.Unix()+int64(offset), 0)
  156. c.SetDateTimeWithFormat(TimeToExcelTime(t.In(timeLocationUTC)), options.ExcelTimeFormat)
  157. }
  158. func (c *Cell) SetDateTimeWithFormat(n float64, format string) {
  159. c.Value = strconv.FormatFloat(n, 'f', -1, 64)
  160. c.NumFmt = format
  161. c.formula = ""
  162. c.cellType = CellTypeNumeric
  163. }
  164. // Float returns the value of cell as a number.
  165. func (c *Cell) Float() (float64, error) {
  166. f, err := strconv.ParseFloat(c.Value, 64)
  167. if err != nil {
  168. return math.NaN(), err
  169. }
  170. return f, nil
  171. }
  172. // SetInt64 sets a cell's value to a 64-bit integer.
  173. func (c *Cell) SetInt64(n int64) {
  174. c.SetValue(n)
  175. }
  176. // Int64 returns the value of cell as 64-bit integer.
  177. func (c *Cell) Int64() (int64, error) {
  178. f, err := strconv.ParseInt(c.Value, 10, 64)
  179. if err != nil {
  180. return -1, err
  181. }
  182. return f, nil
  183. }
  184. // GeneralNumeric returns the value of the cell as a string. It is formatted very closely to the the XLSX spec for how
  185. // to display values when the storage type is Number and the format type is General. It is not 100% identical to the
  186. // spec but is as close as you can get using the built in Go formatting tools.
  187. func (c *Cell) GeneralNumeric() (string, error) {
  188. return generalNumericScientific(c.Value, true)
  189. }
  190. // GeneralNumericWithoutScientific returns numbers that are always formatted as numbers, but it does not follow
  191. // the rules for when XLSX should switch to scientific notation, since sometimes scientific notation is not desired,
  192. // even if that is how the document is supposed to be formatted.
  193. func (c *Cell) GeneralNumericWithoutScientific() (string, error) {
  194. return generalNumericScientific(c.Value, false)
  195. }
  196. // SetInt sets a cell's value to an integer.
  197. func (c *Cell) SetInt(n int) {
  198. c.SetValue(n)
  199. }
  200. // SetInt sets a cell's value to an integer.
  201. func (c *Cell) SetValue(n interface{}) {
  202. switch t := n.(type) {
  203. case time.Time:
  204. c.SetDateTime(t)
  205. return
  206. case int, int8, int16, int32, int64:
  207. c.setNumeric(fmt.Sprintf("%d", n))
  208. case float64:
  209. // When formatting floats, do not use fmt.Sprintf("%v", n), this will cause numbers below 1e-4 to be printed in
  210. // scientific notation. Scientific notation is not a valid way to store numbers in XML.
  211. // Also not not use fmt.Sprintf("%f", n), this will cause numbers to be stored as X.XXXXXX. Which means that
  212. // numbers will lose precision and numbers with fewer significant digits such as 0 will be stored as 0.000000
  213. // which causes tests to fail.
  214. c.setNumeric(strconv.FormatFloat(t, 'f', -1, 64))
  215. case float32:
  216. c.setNumeric(strconv.FormatFloat(float64(t), 'f', -1, 32))
  217. case string:
  218. c.SetString(t)
  219. case []byte:
  220. c.SetString(string(t))
  221. case nil:
  222. c.SetString("")
  223. default:
  224. c.SetString(fmt.Sprintf("%v", n))
  225. }
  226. }
  227. // setNumeric sets a cell's value to a number
  228. func (c *Cell) setNumeric(s string) {
  229. c.Value = s
  230. c.NumFmt = builtInNumFmt[builtInNumFmtIndex_GENERAL]
  231. c.formula = ""
  232. c.cellType = CellTypeNumeric
  233. }
  234. // Int returns the value of cell as integer.
  235. // Has max 53 bits of precision
  236. // See: float64(int64(math.MaxInt))
  237. func (c *Cell) Int() (int, error) {
  238. f, err := strconv.ParseFloat(c.Value, 64)
  239. if err != nil {
  240. return -1, err
  241. }
  242. return int(f), nil
  243. }
  244. // SetBool sets a cell's value to a boolean.
  245. func (c *Cell) SetBool(b bool) {
  246. if b {
  247. c.Value = "1"
  248. } else {
  249. c.Value = "0"
  250. }
  251. c.cellType = CellTypeBool
  252. }
  253. // Bool returns a boolean from a cell's value.
  254. // TODO: Determine if the current return value is
  255. // appropriate for types other than CellTypeBool.
  256. func (c *Cell) Bool() bool {
  257. // If bool, just return the value.
  258. if c.cellType == CellTypeBool {
  259. return c.Value == "1"
  260. }
  261. // If numeric, base it on a non-zero.
  262. if c.cellType == CellTypeNumeric {
  263. return c.Value != "0"
  264. }
  265. // Return whether there's an empty string.
  266. return c.Value != ""
  267. }
  268. // SetFormula sets the format string for a cell.
  269. func (c *Cell) SetFormula(formula string) {
  270. c.formula = formula
  271. c.cellType = CellTypeNumeric
  272. }
  273. func (c *Cell) SetStringFormula(formula string) {
  274. c.formula = formula
  275. c.cellType = CellTypeStringFormula
  276. }
  277. // Formula returns the formula string for the cell.
  278. func (c *Cell) Formula() string {
  279. return c.formula
  280. }
  281. // GetStyle returns the Style associated with a Cell
  282. func (c *Cell) GetStyle() *Style {
  283. if c.style == nil {
  284. c.style = NewStyle()
  285. }
  286. return c.style
  287. }
  288. // SetStyle sets the style of a cell.
  289. func (c *Cell) SetStyle(style *Style) {
  290. c.style = style
  291. }
  292. // GetNumberFormat returns the number format string for a cell.
  293. func (c *Cell) GetNumberFormat() string {
  294. return c.NumFmt
  295. }
  296. func (c *Cell) formatToFloat(format string) (string, error) {
  297. f, err := strconv.ParseFloat(c.Value, 64)
  298. if err != nil {
  299. return c.Value, err
  300. }
  301. return fmt.Sprintf(format, f), nil
  302. }
  303. func (c *Cell) formatToInt(format string) (string, error) {
  304. f, err := strconv.ParseFloat(c.Value, 64)
  305. if err != nil {
  306. return c.Value, err
  307. }
  308. return fmt.Sprintf(format, int(f)), nil
  309. }
  310. // getNumberFormat will update the parsedNumFmt struct if it has become out of date, since a cell's NumFmt string is a
  311. // public field that could be edited by clients.
  312. func (c *Cell) getNumberFormat() *parsedNumberFormat {
  313. if c.parsedNumFmt == nil || c.parsedNumFmt.numFmt != c.NumFmt {
  314. c.parsedNumFmt = parseFullNumberFormatString(c.NumFmt)
  315. }
  316. return c.parsedNumFmt
  317. }
  318. // FormattedValue returns a value, and possibly an error condition
  319. // from a Cell. If it is possible to apply a format to the cell
  320. // value, it will do so, if not then an error will be returned, along
  321. // with the raw value of the Cell.
  322. func (c *Cell) FormattedValue() (string, error) {
  323. fullFormat := c.getNumberFormat()
  324. returnVal, err := fullFormat.FormatValue(c)
  325. if fullFormat.parseEncounteredError != nil {
  326. return returnVal, *fullFormat.parseEncounteredError
  327. }
  328. return returnVal, err
  329. }
  330. // SetDataValidation set data validation
  331. func (c *Cell) SetDataValidation(dd *xlsxCellDataValidation) {
  332. c.DataValidation = dd
  333. }