cell.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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. var timeLocationUTC, _ = time.LoadLocation("UTC")
  115. func TimeToUTCTime(t time.Time) time.Time {
  116. return time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), timeLocationUTC)
  117. }
  118. func TimeToExcelTime(t time.Time) float64 {
  119. return float64(t.UnixNano())/8.64e13 + 25569.0
  120. }
  121. // DateTimeOptions are additional options for exporting times
  122. type DateTimeOptions struct {
  123. // Location allows calculating times in other timezones/locations
  124. Location *time.Location
  125. // ExcelTimeFormat is the string you want excel to use to format the datetime
  126. ExcelTimeFormat string
  127. }
  128. var (
  129. DefaultDateFormat = builtInNumFmt[14]
  130. DefaultDateTimeFormat = builtInNumFmt[22]
  131. DefaultDateOptions = DateTimeOptions{
  132. Location: timeLocationUTC,
  133. ExcelTimeFormat: DefaultDateFormat,
  134. }
  135. DefaultDateTimeOptions = DateTimeOptions{
  136. Location: timeLocationUTC,
  137. ExcelTimeFormat: DefaultDateTimeFormat,
  138. }
  139. )
  140. // SetDate sets the value of a cell to a float.
  141. func (c *Cell) SetDate(t time.Time) {
  142. c.SetDateWithOptions(t, DefaultDateOptions)
  143. }
  144. func (c *Cell) SetDateTime(t time.Time) {
  145. c.SetDateWithOptions(t, DefaultDateTimeOptions)
  146. }
  147. // SetDateWithOptions allows for more granular control when exporting dates and times
  148. func (c *Cell) SetDateWithOptions(t time.Time, options DateTimeOptions) {
  149. _, offset := t.In(options.Location).Zone()
  150. t = time.Unix(t.Unix()+int64(offset), 0)
  151. c.SetDateTimeWithFormat(TimeToExcelTime(t.In(timeLocationUTC)), options.ExcelTimeFormat)
  152. }
  153. func (c *Cell) SetDateTimeWithFormat(n float64, format string) {
  154. c.Value = strconv.FormatFloat(n, 'f', -1, 64)
  155. c.NumFmt = format
  156. c.formula = ""
  157. c.cellType = CellTypeNumeric
  158. }
  159. // Float returns the value of cell as a number.
  160. func (c *Cell) Float() (float64, error) {
  161. f, err := strconv.ParseFloat(c.Value, 64)
  162. if err != nil {
  163. return math.NaN(), err
  164. }
  165. return f, nil
  166. }
  167. // SetInt64 sets a cell's value to a 64-bit integer.
  168. func (c *Cell) SetInt64(n int64) {
  169. c.SetValue(n)
  170. }
  171. // Int64 returns the value of cell as 64-bit integer.
  172. func (c *Cell) Int64() (int64, error) {
  173. f, err := strconv.ParseInt(c.Value, 10, 64)
  174. if err != nil {
  175. return -1, err
  176. }
  177. return f, nil
  178. }
  179. // GeneralNumeric returns the value of the cell as a string. It is formatted very closely to the the XLSX spec for how
  180. // to display values when the storage type is Number and the format type is General. It is not 100% identical to the
  181. // spec but is as close as you can get using the built in Go formatting tools.
  182. func (c *Cell) GeneralNumeric() (string, error) {
  183. return generalNumericScientific(c.Value, true)
  184. }
  185. // GeneralNumericWithoutScientific returns numbers that are always formatted as numbers, but it does not follow
  186. // the rules for when XLSX should switch to scientific notation, since sometimes scientific notation is not desired,
  187. // even if that is how the document is supposed to be formatted.
  188. func (c *Cell) GeneralNumericWithoutScientific() (string, error) {
  189. return generalNumericScientific(c.Value, false)
  190. }
  191. // SetInt sets a cell's value to an integer.
  192. func (c *Cell) SetInt(n int) {
  193. c.SetValue(n)
  194. }
  195. // SetInt sets a cell's value to an integer.
  196. func (c *Cell) SetValue(n interface{}) {
  197. switch t := n.(type) {
  198. case time.Time:
  199. c.SetDateTime(t)
  200. return
  201. case int, int8, int16, int32, int64:
  202. c.setNumeric(fmt.Sprintf("%d", n))
  203. case float64:
  204. // When formatting floats, do not use fmt.Sprintf("%v", n), this will cause numbers below 1e-4 to be printed in
  205. // scientific notation. Scientific notation is not a valid way to store numbers in XML.
  206. // Also not not use fmt.Sprintf("%f", n), this will cause numbers to be stored as X.XXXXXX. Which means that
  207. // numbers will lose precision and numbers with fewer significant digits such as 0 will be stored as 0.000000
  208. // which causes tests to fail.
  209. c.setNumeric(strconv.FormatFloat(t, 'f', -1, 64))
  210. case float32:
  211. c.setNumeric(strconv.FormatFloat(float64(t), 'f', -1, 32))
  212. case string:
  213. c.SetString(t)
  214. case []byte:
  215. c.SetString(string(t))
  216. case nil:
  217. c.SetString("")
  218. default:
  219. c.SetString(fmt.Sprintf("%v", n))
  220. }
  221. }
  222. // setNumeric sets a cell's value to a number
  223. func (c *Cell) setNumeric(s string) {
  224. c.Value = s
  225. c.NumFmt = builtInNumFmt[builtInNumFmtIndex_GENERAL]
  226. c.formula = ""
  227. c.cellType = CellTypeNumeric
  228. }
  229. // Int returns the value of cell as integer.
  230. // Has max 53 bits of precision
  231. // See: float64(int64(math.MaxInt))
  232. func (c *Cell) Int() (int, error) {
  233. f, err := strconv.ParseFloat(c.Value, 64)
  234. if err != nil {
  235. return -1, err
  236. }
  237. return int(f), nil
  238. }
  239. // SetBool sets a cell's value to a boolean.
  240. func (c *Cell) SetBool(b bool) {
  241. if b {
  242. c.Value = "1"
  243. } else {
  244. c.Value = "0"
  245. }
  246. c.cellType = CellTypeBool
  247. }
  248. // Bool returns a boolean from a cell's value.
  249. // TODO: Determine if the current return value is
  250. // appropriate for types other than CellTypeBool.
  251. func (c *Cell) Bool() bool {
  252. // If bool, just return the value.
  253. if c.cellType == CellTypeBool {
  254. return c.Value == "1"
  255. }
  256. // If numeric, base it on a non-zero.
  257. if c.cellType == CellTypeNumeric {
  258. return c.Value != "0"
  259. }
  260. // Return whether there's an empty string.
  261. return c.Value != ""
  262. }
  263. // SetFormula sets the format string for a cell.
  264. func (c *Cell) SetFormula(formula string) {
  265. c.formula = formula
  266. c.cellType = CellTypeNumeric
  267. }
  268. func (c *Cell) SetStringFormula(formula string) {
  269. c.formula = formula
  270. c.cellType = CellTypeStringFormula
  271. }
  272. // Formula returns the formula string for the cell.
  273. func (c *Cell) Formula() string {
  274. return c.formula
  275. }
  276. // GetStyle returns the Style associated with a Cell
  277. func (c *Cell) GetStyle() *Style {
  278. if c.style == nil {
  279. c.style = NewStyle()
  280. }
  281. return c.style
  282. }
  283. // SetStyle sets the style of a cell.
  284. func (c *Cell) SetStyle(style *Style) {
  285. c.style = style
  286. }
  287. // GetNumberFormat returns the number format string for a cell.
  288. func (c *Cell) GetNumberFormat() string {
  289. return c.NumFmt
  290. }
  291. func (c *Cell) formatToFloat(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, f), nil
  297. }
  298. func (c *Cell) formatToInt(format string) (string, error) {
  299. f, err := strconv.ParseFloat(c.Value, 64)
  300. if err != nil {
  301. return c.Value, err
  302. }
  303. return fmt.Sprintf(format, int(f)), nil
  304. }
  305. // getNumberFormat will update the parsedNumFmt struct if it has become out of date, since a cell's NumFmt string is a
  306. // public field that could be edited by clients.
  307. func (c *Cell) getNumberFormat() *parsedNumberFormat {
  308. if c.parsedNumFmt == nil || c.parsedNumFmt.numFmt != c.NumFmt {
  309. c.parsedNumFmt = parseFullNumberFormatString(c.NumFmt)
  310. }
  311. return c.parsedNumFmt
  312. }
  313. // FormattedValue returns a value, and possibly an error condition
  314. // from a Cell. If it is possible to apply a format to the cell
  315. // value, it will do so, if not then an error will be returned, along
  316. // with the raw value of the Cell.
  317. func (c *Cell) FormattedValue() (string, error) {
  318. fullFormat := c.getNumberFormat()
  319. returnVal, err := fullFormat.FormatValue(c)
  320. if fullFormat.parseEncounteredError != nil {
  321. return returnVal, *fullFormat.parseEncounteredError
  322. }
  323. return returnVal, err
  324. }