cell.go 10 KB

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