cell.go 10 KB

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