-
Notifications
You must be signed in to change notification settings - Fork 267
/
ExcelDataValidation.cs
588 lines (538 loc) · 19.8 KB
/
ExcelDataValidation.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
/*************************************************************************************************
Required Notice: Copyright (C) EPPlus Software AB.
This software is licensed under PolyForm Noncommercial License 1.0.0
and may only be used for noncommercial purposes
https://polyformproject.org/licenses/noncommercial/1.0.0/
A commercial license to use this software can be purchased at https://epplussoftware.com
*************************************************************************************************
Date Author Change
*************************************************************************************************
01/27/2020 EPPlus Software AB Initial release EPPlus 5
*************************************************************************************************/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using OfficeOpenXml.Utils;
using System.Xml;
using System.Text.RegularExpressions;
using OfficeOpenXml.DataValidation.Formulas.Contracts;
using OfficeOpenXml.DataValidation.Contracts;
using OfficeOpenXml.DataValidation.Exceptions;
namespace OfficeOpenXml.DataValidation
{
/// <summary>
/// Abstract base class for all Excel datavalidations. Contains functionlity which is common for all these different validation types.
/// </summary>
public abstract class ExcelDataValidation : XmlHelper, IExcelDataValidation
{
private const string ItemElementNodeName = "d:dataValidation";
private const string ExtLstElementNodeName = "x14:dataValidation";
private readonly string _uidPath = "@xr:uid";
private readonly string _errorStylePath = "@errorStyle";
private readonly string _errorTitlePath = "@errorTitle";
private readonly string _errorPath = "@error";
private readonly string _promptTitlePath = "@promptTitle";
private readonly string _promptPath = "@prompt";
private readonly string _operatorPath = "@operator";
private readonly string _showErrorMessagePath = "@showErrorMessage";
private readonly string _showInputMessagePath = "@showInputMessage";
private readonly string _typeMessagePath = "@type";
private readonly string _sqrefPath = "@sqref";
private readonly string _sqrefPathExt = "xm:sqref";
private readonly string _allowBlankPath = "@allowBlank";
/// <summary>
/// Xml path for Formula1
/// </summary>
private readonly string _formula1Path = "d:formula1";
private readonly string _formula1ExtLstPath = "x14:formula1/xm:f";
/// <summary>
/// Xml path for Formula2
/// </summary>
private readonly string _formula2Path = "d:formula2";
private readonly string _formula2ExtLstPath = "x14:formula2/xm:f";
internal ExcelDataValidation(ExcelWorksheet worksheet, string uid, string address, ExcelDataValidationType validationType, InternalValidationType internalValidationType = InternalValidationType.DataValidation)
: this(worksheet, uid, address, validationType, null, internalValidationType)
{ }
/// <summary>
/// Constructor
/// </summary>
/// <param name="worksheet">worksheet that owns the validation</param>
/// <param name="uid">Uid of the data validation, format should be a Guid surrounded by curly braces.</param>
/// <param name="itemElementNode">Xml top node (dataValidations)</param>
/// <param name="validationType">Data validation type</param>
/// <param name="address">address for data validation</param>
/// <param name="internalValidationType">If the datavalidation is internal or in the extLst element</param>
internal ExcelDataValidation(ExcelWorksheet worksheet, string uid, string address, ExcelDataValidationType validationType, XmlNode itemElementNode, InternalValidationType internalValidationType = InternalValidationType.DataValidation)
: this(worksheet, uid, address, validationType, itemElementNode, null, internalValidationType)
{
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="worksheet">worksheet that owns the validation</param>
/// <param name="uid">Uid of the data validation, format should be a Guid surrounded by curly braces.</param>
/// <param name="itemElementNode">Xml top node (dataValidations) when importing xml</param>
/// <param name="validationType">Data validation type</param>
/// <param name="address">address for data validation</param>
/// <param name="namespaceManager">Xml Namespace manager</param>
/// <param name="internalValidationType"><see cref="InternalValidationType"/></param>
internal ExcelDataValidation(ExcelWorksheet worksheet, string uid, string address, ExcelDataValidationType validationType, XmlNode itemElementNode, XmlNamespaceManager namespaceManager, InternalValidationType internalValidationType = InternalValidationType.DataValidation)
: base(namespaceManager != null ? namespaceManager : worksheet.NameSpaceManager)
{
Require.Argument(uid).IsNotNullOrEmpty("uid");
Require.Argument(address).IsNotNullOrEmpty("address");
InternalValidationType = internalValidationType;
InitNodeOrder(validationType);
address = CheckAndFixRangeAddress(address);
if (itemElementNode == null)
{
TopNode = worksheet.WorksheetXml.SelectSingleNode(GetTopNodeName(), worksheet.NameSpaceManager);
itemElementNode = CreateNode(GetItemElementNodeName(), false, true);
TopNode.AppendChild(itemElementNode);
}
TopNode = itemElementNode;
ValidationType = validationType;
Uid = uid;
Address = new ExcelAddress(address);
}
private bool _isStale = false;
/// <summary>
/// Indicates whether this instance is stale, see https://github.com/EPPlusSoftware/EPPlus/wiki/Data-validation-Exceptions
/// </summary>
bool IExcelDataValidation.IsStale
{
get
{
return _isStale;
}
}
internal void SetStale()
{
_isStale = true;
}
protected void CheckIfStale()
{
if (_isStale)
{
throw new DataValidationStaleException("This instance of Data validation is stale. Ensure that you set all other properties before you set the Formula.ExcelFormula property. See https://github.com/EPPlusSoftware/EPPlus/wiki/Data-validation-Exceptions for more details.");
}
}
internal InternalValidationType InternalValidationType { get; private set; } = InternalValidationType.DataValidation;
internal virtual void RegisterFormulaListener(DataValidationFormulaListener listener)
{
}
private string GetSqRefPath()
{
return InternalValidationType == InternalValidationType.DataValidation ? _sqrefPath : _sqrefPathExt;
}
private string GetItemElementNodeName()
{
return InternalValidationType == InternalValidationType.DataValidation ? ItemElementNodeName : ExtLstElementNodeName;
}
private string GetTopNodeName()
{
return InternalValidationType == InternalValidationType.DataValidation ? "//d:dataValidations" : "//d:extLst/d:ext/x14:dataValidations";
}
private void InitNodeOrder(ExcelDataValidationType validationType)
{
// set schema node order
if(validationType == ExcelDataValidationType.List || validationType == ExcelDataValidationType.Custom)
{
if(InternalValidationType == InternalValidationType.DataValidation)
{
SchemaNodeOrder = new string[]{
"uid",
"type",
"errorStyle",
"showDropDown",
"allowBlank",
"showInputMessage",
"showErrorMessage",
"errorTitle",
"error",
"promptTitle",
"prompt",
"sqref",
"formula1"
};
}
else
{
SchemaNodeOrder = new string[]{
"uid",
"type",
"errorStyle",
"showDropDown",
"allowBlank",
"showInputMessage",
"showErrorMessage",
"errorTitle",
"error",
"promptTitle",
"prompt",
"formula1",
"sqref"
};
}
}
else
{
SchemaNodeOrder = new string[]{
"uid",
"type",
"errorStyle",
"operator",
"allowBlank",
"showInputMessage",
"showErrorMessage",
"errorTitle",
"error",
"promptTitle",
"prompt",
"sqref",
"formula1",
"formula2"
};
}
}
private string CheckAndFixRangeAddress(string address)
{
if (address.Contains(','))
{
throw new FormatException("Multiple addresses may not be commaseparated, use space instead");
}
address = ConvertUtil._invariantTextInfo.ToUpper(address);
if (Regex.IsMatch(address, @"[A-Z]+:[A-Z]+"))
{
address = AddressUtility.ParseEntireColumnSelections(address);
}
return address;
}
protected void SetNullableBoolValue(string path, bool? val)
{
if (val.HasValue)
{
SetXmlNodeBool(path, val.Value);
}
else
{
DeleteNode(path);
}
}
/// <summary>
/// This method will validate the state of the validation
/// </summary>
/// <exception cref="InvalidOperationException">If the state breaks the rules of the validation</exception>
public virtual void Validate()
{
var address = Address.Address;
// validate Formula1
if (string.IsNullOrEmpty(Formula1Internal) && !(AllowBlank ?? false))
{
throw new InvalidOperationException("Validation of " + address + " failed: Formula1 cannot be empty");
}
}
internal void Delete()
{
DeleteTopNode();
}
#region Public properties
/// <summary>
/// True if the validation type allows operator to be set.
/// </summary>
public bool AllowsOperator
{
get
{
return ValidationType.AllowOperator;
}
}
public string Uid
{
get
{
return GetXmlNodeString(_uidPath);
}
set
{
CheckIfStale();
if (string.IsNullOrEmpty(value)) throw new ArgumentNullException("Uid");
var uid = value.TrimStart('{').TrimEnd('}');
SetXmlNodeString(_uidPath, "{" + uid + "}");
}
}
/// <summary>
/// Address of data validation
/// </summary>
public ExcelAddress Address
{
get
{
return new ExcelAddress(GetXmlNodeString(GetSqRefPath()).Replace(" ", ","));
}
private set
{
SetAddress(value.Address);
}
}
/// <summary>
/// Validation type
/// </summary>
public ExcelDataValidationType ValidationType
{
get
{
var typeString = GetXmlNodeString(_typeMessagePath);
return ExcelDataValidationType.GetBySchemaName(typeString);
}
private set
{
SetXmlNodeString(_typeMessagePath, value.SchemaName, true);
}
}
/// <summary>
/// Operator for comparison between the entered value and Formula/Formulas.
/// </summary>
public ExcelDataValidationOperator Operator
{
get
{
var operatorString = GetXmlNodeString(_operatorPath);
if (!string.IsNullOrEmpty(operatorString))
{
return (ExcelDataValidationOperator)Enum.Parse(typeof(ExcelDataValidationOperator), operatorString);
}
return default(ExcelDataValidationOperator);
}
set
{
if (!ValidationType.AllowOperator)
{
throw new InvalidOperationException("The current validation type does not allow operator to be set");
}
CheckIfStale();
SetXmlNodeString(_operatorPath, value.ToString());
}
}
/// <summary>
/// Warning style
/// </summary>
public ExcelDataValidationWarningStyle ErrorStyle
{
get
{
var errorStyleString = GetXmlNodeString(_errorStylePath);
if (!string.IsNullOrEmpty(errorStyleString))
{
return (ExcelDataValidationWarningStyle)Enum.Parse(typeof(ExcelDataValidationWarningStyle), errorStyleString);
}
return ExcelDataValidationWarningStyle.undefined;
}
set
{
if (value == ExcelDataValidationWarningStyle.undefined)
{
DeleteNode(_errorStylePath);
}
else
{
CheckIfStale();
SetXmlNodeString(_errorStylePath, value.ToString());
}
}
}
/// <summary>
/// True if blanks should be allowed
/// </summary>
public bool? AllowBlank
{
get
{
return GetXmlNodeBoolNullable(_allowBlankPath);
}
set
{
CheckIfStale();
SetNullableBoolValue(_allowBlankPath, value);
}
}
/// <summary>
/// True if input message should be shown
/// </summary>
public bool? ShowInputMessage
{
get
{
return GetXmlNodeBoolNullable(_showInputMessagePath);
}
set
{
CheckIfStale();
SetNullableBoolValue(_showInputMessagePath, value);
}
}
/// <summary>
/// True if error message should be shown
/// </summary>
public bool? ShowErrorMessage
{
get
{
return GetXmlNodeBoolNullable(_showErrorMessagePath);
}
set
{
CheckIfStale();
SetNullableBoolValue(_showErrorMessagePath, value);
}
}
/// <summary>
/// Title of error message box
/// </summary>
public string ErrorTitle
{
get
{
return GetXmlNodeString(_errorTitlePath);
}
set
{
if (string.IsNullOrEmpty(value))
{
DeleteNode(_errorTitlePath);
}
else
{
CheckIfStale();
SetXmlNodeString(_errorTitlePath, value.ToString());
}
}
}
/// <summary>
/// Error message box text
/// </summary>
public string Error
{
get
{
return GetXmlNodeString(_errorPath);
}
set
{
if (string.IsNullOrEmpty(value))
{
DeleteNode(_errorPath);
}
else
{
CheckIfStale();
SetXmlNodeString(_errorPath, value.ToString());
}
}
}
/// <summary>
/// Title of the validation message box.
/// </summary>
public string PromptTitle
{
get
{
return GetXmlNodeString(_promptTitlePath);
}
set
{
CheckIfStale();
SetXmlNodeString(_promptTitlePath, value);
}
}
/// <summary>
/// Text of the validation message box.
/// </summary>
public string Prompt
{
get
{
return GetXmlNodeString(_promptPath);
}
set
{
CheckIfStale();
SetXmlNodeString(_promptPath, value);
}
}
/// <summary>
/// Formula 1
/// </summary>
protected string Formula1Internal
{
get
{
return GetXmlNodeString(GetFormula1Path());
}
}
/// <summary>
/// Formula 2
/// </summary>
protected string Formula2Internal
{
get
{
return GetXmlNodeString(GetFormula2Path());
}
}
#endregion
#region Internal properties
internal static string NewId()
{
return "{" + Guid.NewGuid().ToString().ToUpperInvariant() + "}";
}
internal bool IsExtLst { get; set; }
ExcelDataValidationAsType _as = null;
/// <summary>
/// Us this property to case <see cref="IExcelDataValidation"/>s to its subtypes
/// </summary>
public ExcelDataValidationAsType As
{
get
{
if(_as == null)
{
_as = new ExcelDataValidationAsType(this);
}
return _as;
}
}
#endregion
/// <summary>
/// Sets the value to the supplied path
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="val">The value to set</param>
/// <param name="path">xml path</param>
protected void SetValue<T>(Nullable<T> val, string path)
where T : struct
{
if (!val.HasValue)
{
DeleteNode(path);
}
var stringValue = val.Value.ToString().Replace(',', '.');
SetXmlNodeString(path, stringValue);
}
protected string GetFormula1Path()
{
return InternalValidationType == InternalValidationType.DataValidation ? _formula1Path : _formula1ExtLstPath;
}
protected string GetFormula2Path()
{
return InternalValidationType == InternalValidationType.DataValidation ? _formula2Path : _formula2ExtLstPath;
}
internal void SetAddress(string address)
{
var dvAddress = AddressUtility.ParseEntireColumnSelections(address);
SetXmlNodeString(GetSqRefPath(), dvAddress.Replace(",", " "));
}
}
}