datavalidation.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. // Copyright 2016 - 2021 The excelize Authors. All rights reserved. Use of
  2. // this source code is governed by a BSD-style license that can be found in
  3. // the LICENSE file.
  4. //
  5. // Package excelize providing a set of functions that allow you to write to
  6. // and read from XLSX / XLSM / XLTM files. Supports reading and writing
  7. // spreadsheet documents generated by Microsoft Excel™ 2007 and later. Supports
  8. // complex components by high compatibility, and provided streaming API for
  9. // generating or reading data from a worksheet with huge amounts of data. This
  10. // library needs Go version 1.15 or later.
  11. package excelize
  12. import (
  13. "fmt"
  14. "strings"
  15. )
  16. // DataValidationType defined the type of data validation.
  17. type DataValidationType int
  18. // Data validation types.
  19. const (
  20. _DataValidationType = iota
  21. typeNone // inline use
  22. DataValidationTypeCustom
  23. DataValidationTypeDate
  24. DataValidationTypeDecimal
  25. typeList // inline use
  26. DataValidationTypeTextLeng
  27. DataValidationTypeTime
  28. // DataValidationTypeWhole Integer
  29. DataValidationTypeWhole
  30. )
  31. const (
  32. // dataValidationFormulaStrLen 255 characters+ 2 quotes
  33. dataValidationFormulaStrLen = 257
  34. // dataValidationFormulaStrLenErr
  35. dataValidationFormulaStrLenErr = "data validation must be 0-255 characters"
  36. )
  37. // DataValidationErrorStyle defined the style of data validation error alert.
  38. type DataValidationErrorStyle int
  39. // Data validation error styles.
  40. const (
  41. _ DataValidationErrorStyle = iota
  42. DataValidationErrorStyleStop
  43. DataValidationErrorStyleWarning
  44. DataValidationErrorStyleInformation
  45. )
  46. // Data validation error styles.
  47. const (
  48. styleStop = "stop"
  49. styleWarning = "warning"
  50. styleInformation = "information"
  51. )
  52. // DataValidationOperator operator enum.
  53. type DataValidationOperator int
  54. // Data validation operators.
  55. const (
  56. _DataValidationOperator = iota
  57. DataValidationOperatorBetween
  58. DataValidationOperatorEqual
  59. DataValidationOperatorGreaterThan
  60. DataValidationOperatorGreaterThanOrEqual
  61. DataValidationOperatorLessThan
  62. DataValidationOperatorLessThanOrEqual
  63. DataValidationOperatorNotBetween
  64. DataValidationOperatorNotEqual
  65. )
  66. // NewDataValidation return data validation struct.
  67. func NewDataValidation(allowBlank bool) *DataValidation {
  68. return &DataValidation{
  69. AllowBlank: allowBlank,
  70. ShowErrorMessage: false,
  71. ShowInputMessage: false,
  72. }
  73. }
  74. // SetError set error notice.
  75. func (dd *DataValidation) SetError(style DataValidationErrorStyle, title, msg string) {
  76. dd.Error = &msg
  77. dd.ErrorTitle = &title
  78. strStyle := styleStop
  79. switch style {
  80. case DataValidationErrorStyleStop:
  81. strStyle = styleStop
  82. case DataValidationErrorStyleWarning:
  83. strStyle = styleWarning
  84. case DataValidationErrorStyleInformation:
  85. strStyle = styleInformation
  86. }
  87. dd.ShowErrorMessage = true
  88. dd.ErrorStyle = &strStyle
  89. }
  90. // SetInput set prompt notice.
  91. func (dd *DataValidation) SetInput(title, msg string) {
  92. dd.ShowInputMessage = true
  93. dd.PromptTitle = &title
  94. dd.Prompt = &msg
  95. }
  96. // SetDropList data validation list.
  97. func (dd *DataValidation) SetDropList(keys []string) error {
  98. formula := "\"" + strings.Join(keys, ",") + "\""
  99. if dataValidationFormulaStrLen < len(formula) {
  100. return fmt.Errorf(dataValidationFormulaStrLenErr)
  101. }
  102. dd.Formula1 = fmt.Sprintf("<formula1>%s</formula1>", formula)
  103. dd.Type = convDataValidationType(typeList)
  104. return nil
  105. }
  106. // SetRange provides function to set data validation range in drop list.
  107. func (dd *DataValidation) SetRange(f1, f2 float64, t DataValidationType, o DataValidationOperator) error {
  108. formula1 := fmt.Sprintf("%f", f1)
  109. formula2 := fmt.Sprintf("%f", f2)
  110. if dataValidationFormulaStrLen+21 < len(dd.Formula1) || dataValidationFormulaStrLen+21 < len(dd.Formula2) {
  111. return fmt.Errorf(dataValidationFormulaStrLenErr)
  112. }
  113. dd.Formula1 = fmt.Sprintf("<formula1>%s</formula1>", formula1)
  114. dd.Formula2 = fmt.Sprintf("<formula2>%s</formula2>", formula2)
  115. dd.Type = convDataValidationType(t)
  116. dd.Operator = convDataValidationOperatior(o)
  117. return nil
  118. }
  119. // SetSqrefDropList provides set data validation on a range with source
  120. // reference range of the worksheet by given data validation object and
  121. // worksheet name. The data validation object can be created by
  122. // NewDataValidation function. For example, set data validation on
  123. // Sheet1!A7:B8 with validation criteria source Sheet1!E1:E3 settings, create
  124. // in-cell dropdown by allowing list source:
  125. //
  126. // dvRange := excelize.NewDataValidation(true)
  127. // dvRange.Sqref = "A7:B8"
  128. // dvRange.SetSqrefDropList("$E$1:$E$3", true)
  129. // f.AddDataValidation("Sheet1", dvRange)
  130. //
  131. func (dd *DataValidation) SetSqrefDropList(sqref string, isCurrentSheet bool) error {
  132. if isCurrentSheet {
  133. dd.Formula1 = fmt.Sprintf("<formula1>%s</formula1>", sqref)
  134. dd.Type = convDataValidationType(typeList)
  135. return nil
  136. }
  137. return fmt.Errorf("cross-sheet sqref cell are not supported")
  138. }
  139. // SetSqref provides function to set data validation range in drop list.
  140. func (dd *DataValidation) SetSqref(sqref string) {
  141. if dd.Sqref == "" {
  142. dd.Sqref = sqref
  143. } else {
  144. dd.Sqref = fmt.Sprintf("%s %s", dd.Sqref, sqref)
  145. }
  146. }
  147. // convDataValidationType get excel data validation type.
  148. func convDataValidationType(t DataValidationType) string {
  149. typeMap := map[DataValidationType]string{
  150. typeNone: "none",
  151. DataValidationTypeCustom: "custom",
  152. DataValidationTypeDate: "date",
  153. DataValidationTypeDecimal: "decimal",
  154. typeList: "list",
  155. DataValidationTypeTextLeng: "textLength",
  156. DataValidationTypeTime: "time",
  157. DataValidationTypeWhole: "whole",
  158. }
  159. return typeMap[t]
  160. }
  161. // convDataValidationOperatior get excel data validation operator.
  162. func convDataValidationOperatior(o DataValidationOperator) string {
  163. typeMap := map[DataValidationOperator]string{
  164. DataValidationOperatorBetween: "between",
  165. DataValidationOperatorEqual: "equal",
  166. DataValidationOperatorGreaterThan: "greaterThan",
  167. DataValidationOperatorGreaterThanOrEqual: "greaterThanOrEqual",
  168. DataValidationOperatorLessThan: "lessThan",
  169. DataValidationOperatorLessThanOrEqual: "lessThanOrEqual",
  170. DataValidationOperatorNotBetween: "notBetween",
  171. DataValidationOperatorNotEqual: "notEqual",
  172. }
  173. return typeMap[o]
  174. }
  175. // AddDataValidation provides set data validation on a range of the worksheet
  176. // by given data validation object and worksheet name. The data validation
  177. // object can be created by NewDataValidation function.
  178. //
  179. // Example 1, set data validation on Sheet1!A1:B2 with validation criteria
  180. // settings, show error alert after invalid data is entered with "Stop" style
  181. // and custom title "error body":
  182. //
  183. // dvRange := excelize.NewDataValidation(true)
  184. // dvRange.Sqref = "A1:B2"
  185. // dvRange.SetRange(10, 20, excelize.DataValidationTypeWhole, excelize.DataValidationOperatorBetween)
  186. // dvRange.SetError(excelize.DataValidationErrorStyleStop, "error title", "error body")
  187. // err := f.AddDataValidation("Sheet1", dvRange)
  188. //
  189. // Example 2, set data validation on Sheet1!A3:B4 with validation criteria
  190. // settings, and show input message when cell is selected:
  191. //
  192. // dvRange = excelize.NewDataValidation(true)
  193. // dvRange.Sqref = "A3:B4"
  194. // dvRange.SetRange(10, 20, excelize.DataValidationTypeWhole, excelize.DataValidationOperatorGreaterThan)
  195. // dvRange.SetInput("input title", "input body")
  196. // err = f.AddDataValidation("Sheet1", dvRange)
  197. //
  198. // Example 3, set data validation on Sheet1!A5:B6 with validation criteria
  199. // settings, create in-cell dropdown by allowing list source:
  200. //
  201. // dvRange = excelize.NewDataValidation(true)
  202. // dvRange.Sqref = "A5:B6"
  203. // dvRange.SetDropList([]string{"1", "2", "3"})
  204. // err = f.AddDataValidation("Sheet1", dvRange)
  205. //
  206. func (f *File) AddDataValidation(sheet string, dv *DataValidation) error {
  207. ws, err := f.workSheetReader(sheet)
  208. if err != nil {
  209. return err
  210. }
  211. if nil == ws.DataValidations {
  212. ws.DataValidations = new(xlsxDataValidations)
  213. }
  214. ws.DataValidations.DataValidation = append(ws.DataValidations.DataValidation, dv)
  215. ws.DataValidations.Count = len(ws.DataValidations.DataValidation)
  216. return err
  217. }
  218. // DeleteDataValidation delete data validation by given worksheet name and
  219. // reference sequence.
  220. func (f *File) DeleteDataValidation(sheet, sqref string) error {
  221. ws, err := f.workSheetReader(sheet)
  222. if err != nil {
  223. return err
  224. }
  225. if ws.DataValidations == nil {
  226. return nil
  227. }
  228. dv := ws.DataValidations
  229. for i := 0; i < len(dv.DataValidation); i++ {
  230. if dv.DataValidation[i].Sqref == sqref {
  231. dv.DataValidation = append(dv.DataValidation[:i], dv.DataValidation[i+1:]...)
  232. i--
  233. }
  234. }
  235. dv.Count = len(dv.DataValidation)
  236. if dv.Count == 0 {
  237. ws.DataValidations = nil
  238. }
  239. return nil
  240. }