cell.go 10 KB

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