Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HivePerformance/sources/HeuristicLab.ExtLibs/HeuristicLab.EPPlus/3.1.3/EPPlus-3.1.3/DataValidation/ExcelDataValidation.cs @ 9616

Last change on this file since 9616 was 9580, checked in by sforsten, 12 years ago

#1730:

  • added SymbolicDataAnalysisExpressionExcelFormatter
  • changed modifiers in SymbolicExpressionTreeChart of methods SaveImageAsBitmap and SaveImageAsEmf to public
  • added menu item ExportSymbolicSolutionToExcelMenuItem to export a symbolic solution to an excel file
  • added EPPlus-3.1.3 to ExtLibs
File size: 13.7 KB
Line 
1/*******************************************************************************
2 * You may amend and distribute as you like, but don't remove this header!
3 *
4 * EPPlus provides server-side generation of Excel 2007/2010 spreadsheets.
5 * See http://www.codeplex.com/EPPlus for details.
6 *
7 * Copyright (C) 2011  Jan Källman
8 *
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
13
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
17 * See the GNU Lesser General Public License for more details.
18 *
19 * The GNU Lesser General Public License can be viewed at http://www.opensource.org/licenses/lgpl-license.php
20 * If you unfamiliar with this license or have questions about it, here is an http://www.gnu.org/licenses/gpl-faq.html
21 *
22 * All code and executables are provided "as is" with no warranty either express or implied.
23 * The author accepts no liability for any damage or loss of business that this product may cause.
24 *
25 * Code change notes:
26 *
27 * Author             Change            Date
28 * ******************************************************************************
29 * Mats Alm                       Added                   2011-01-01
30 * Jan Källman                    License changed GPL-->LGPL  2011-12-27
31 *******************************************************************************/
32using System;
33using System.Collections.Generic;
34using System.Linq;
35using System.Text;
36using OfficeOpenXml.Utils;
37using System.Xml;
38using System.Text.RegularExpressions;
39using OfficeOpenXml.DataValidation.Formulas.Contracts;
40using OfficeOpenXml.DataValidation.Contracts;
41
42namespace OfficeOpenXml.DataValidation
43{
44    /// <summary>
45    /// Excel datavalidation
46    /// </summary>
47    public abstract class ExcelDataValidation : XmlHelper, IExcelDataValidation 
48    {
49        private const string _itemElementNodeName = "d:dataValidation";
50
51
52        private readonly string _errorStylePath = "@errorStyle";
53        private readonly string _errorTitlePath = "@errorTitle";
54        private readonly string _errorPath = "@error";
55        private readonly string _promptTitlePath = "@promptTitle";
56        private readonly string _promptPath = "@prompt";
57        private readonly string _operatorPath = "@operator";
58        private readonly string _showErrorMessagePath = "@showErrorMessage";
59        private readonly string _showInputMessagePath = "@showInputMessage";
60        private readonly string _typeMessagePath = "@type";
61        private readonly string _sqrefPath = "@sqref";
62        private readonly string _allowBlankPath = "@allowBlank";
63        protected readonly string _formula1Path = "d:formula1";
64        protected readonly string _formula2Path = "d:formula2";
65
66        internal ExcelDataValidation(ExcelWorksheet worksheet, string address, ExcelDataValidationType validationType)
67            : this(worksheet, address, validationType, null)
68        { }
69
70        /// <summary>
71        /// Constructor
72        /// </summary>
73        /// <param name="worksheet">worksheet that owns the validation</param>
74        /// <param name="itemElementNode">Xml top node (dataValidations)</param>
75        /// <param name="validationType">Data validation type</param>
76        /// <param name="address">address for data validation</param>
77        internal ExcelDataValidation(ExcelWorksheet worksheet, string address, ExcelDataValidationType validationType, XmlNode itemElementNode)
78            : this(worksheet, address, validationType, itemElementNode, null)
79        {
80
81        }
82
83        /// <summary>
84        /// Constructor
85        /// </summary>
86        /// <param name="worksheet">worksheet that owns the validation</param>
87        /// <param name="itemElementNode">Xml top node (dataValidations) when importing xml</param>
88        /// <param name="validationType">Data validation type</param>
89        /// <param name="address">address for data validation</param>
90        /// <param name="namespaceManager">Xml Namespace manager</param>
91        internal ExcelDataValidation(ExcelWorksheet worksheet, string address, ExcelDataValidationType validationType, XmlNode itemElementNode, XmlNamespaceManager namespaceManager)
92            : base(namespaceManager != null ? namespaceManager : worksheet.NameSpaceManager)
93        {
94            Require.Argument(address).IsNotNullOrEmpty("address");
95            address = CheckAndFixRangeAddress(address);
96            if (itemElementNode == null)
97            {
98                //var xmlDoc = worksheet.WorksheetXml;
99                TopNode = worksheet.WorksheetXml.SelectSingleNode("//d:dataValidations", worksheet.NameSpaceManager);
100                // did not succeed using the XmlHelper methods here... so I'm creating the new node using XmlDocument...
101                var nsUri = NameSpaceManager.LookupNamespace("d");
102                //itemElementNode = TopNode.OwnerDocument.CreateElement(_itemElementNodeName, nsUri);
103                itemElementNode = TopNode.OwnerDocument.CreateElement(_itemElementNodeName.Split(':')[1], nsUri);
104                TopNode.AppendChild(itemElementNode);
105            }
106            TopNode = itemElementNode;
107            ValidationType = validationType;
108            Address = new ExcelAddress(address);
109            if (validationType.AllowOperator)
110            {
111                Operator = ExcelDataValidationOperator.any;
112            }
113            Init();
114        }
115
116        private void Init()
117        {
118            // set schema node order
119            SchemaNodeOrder = new string[]{
120                "type",
121                "errorStyle",
122                "operator",
123                "allowBlank",
124                "showInputMessage",
125                "showErrorMessage",
126                "errorTitle",
127                "error",
128                "promptTitle",
129                "prompt",
130                "sqref",
131                "formula1",
132                "formula2"
133            };
134        }
135
136        private string CheckAndFixRangeAddress(string address)
137        {
138            if (address.Contains(','))
139            {
140                throw new FormatException("Multiple addresses may not be commaseparated, use space instead");
141            }
142            address = address.ToUpper();
143            if (Regex.IsMatch(address, @"[A-Z]+:[A-Z]+"))
144            {
145                address = AddressUtility.ParseEntireColumnSelections(address);
146            }
147            return address;
148        }
149
150        private void SetNullableBoolValue(string path, bool? val)
151        {
152            if (val.HasValue)
153            {
154                SetXmlNodeBool(path, val.Value);
155            }
156            else
157            {
158                DeleteNode(path);
159            }
160        }
161
162        /// <summary>
163        /// This method will validate the state of the validation
164        /// </summary>
165        /// <exception cref="InvalidOperationException">If the state breaks the rules of the validation</exception>
166        public virtual void Validate()
167        {
168            var address = Address.Address;
169            // validate Formula1
170            if (string.IsNullOrEmpty(Formula1Internal))
171            {
172                throw new InvalidOperationException("Validation of " + address + " failed: Formula1 cannot be empty");
173            }
174        }
175
176        #region Public properties
177
178        /// <summary>
179        /// True if the validation type allows operator to be set.
180        /// </summary>
181        public bool AllowsOperator
182        {
183            get
184            {
185                return ValidationType.AllowOperator;
186            }
187        }
188
189        /// <summary>
190        /// Address of data validation
191        /// </summary>
192        public ExcelAddress Address
193        {
194            get
195            {
196                return new ExcelAddress(GetXmlNodeString(_sqrefPath));
197            }
198            private set
199            {
200                var address = AddressUtility.ParseEntireColumnSelections(value.Address);
201                SetXmlNodeString(_sqrefPath, address);
202            }
203        }
204        /// <summary>
205        /// Validation type
206        /// </summary>
207        public ExcelDataValidationType ValidationType
208        {
209            get
210            {
211                var typeString = GetXmlNodeString(_typeMessagePath);
212                return ExcelDataValidationType.GetBySchemaName(typeString);
213            }
214            private set
215            {
216                SetXmlNodeString(_typeMessagePath, value.SchemaName);
217            }
218        }
219
220        /// <summary>
221        /// Operator for comparison between the entered value and Formula/Formulas.
222        /// </summary>
223        public ExcelDataValidationOperator Operator
224        {
225            get
226            {
227                var operatorString = GetXmlNodeString(_operatorPath);
228                if (!string.IsNullOrEmpty(operatorString))
229                {
230                    return (ExcelDataValidationOperator)Enum.Parse(typeof(ExcelDataValidationOperator), operatorString);
231                }
232                return default(ExcelDataValidationOperator);
233            }
234            set
235            {
236                if (!ValidationType.AllowOperator)
237                {
238                    throw new InvalidOperationException("The current validation type does not allow operator to be set");
239                }
240                SetXmlNodeString(_operatorPath, value.ToString());
241            }
242        }
243
244        /// <summary>
245        /// Warning style
246        /// </summary>
247        public ExcelDataValidationWarningStyle ErrorStyle
248        {
249            get
250            {
251                var errorStyleString = GetXmlNodeString(_errorStylePath);
252                if (!string.IsNullOrEmpty(errorStyleString))
253                {
254                    return (ExcelDataValidationWarningStyle)Enum.Parse(typeof(ExcelDataValidationWarningStyle), errorStyleString);
255                }
256                return ExcelDataValidationWarningStyle.undefined;
257            }
258            set
259            {
260                if(value == ExcelDataValidationWarningStyle.undefined)
261                {
262                    DeleteNode(_errorStylePath);
263                }
264                SetXmlNodeString(_errorStylePath, value.ToString());
265            }
266        }
267
268        /// <summary>
269        /// True if blanks should be allowed
270        /// </summary>
271        public bool? AllowBlank
272        {
273            get
274            {
275                return GetXmlNodeBoolNullable(_allowBlankPath);
276            }
277            set
278            {
279                SetNullableBoolValue(_allowBlankPath, value);
280            }
281        }
282
283        /// <summary>
284        /// True if input message should be shown
285        /// </summary>
286        public bool? ShowInputMessage
287        {
288            get
289            {
290                return GetXmlNodeBoolNullable(_showInputMessagePath);
291            }
292            set
293            {
294                SetNullableBoolValue(_showInputMessagePath, value);
295            }
296        }
297
298        /// <summary>
299        /// True if error message should be shown
300        /// </summary>
301        public bool? ShowErrorMessage
302        {
303            get
304            {
305                return GetXmlNodeBoolNullable(_showErrorMessagePath);
306            }
307            set
308            {
309                SetNullableBoolValue(_showErrorMessagePath, value);
310            }
311        }
312
313        /// <summary>
314        /// Title of error message box
315        /// </summary>
316        public string ErrorTitle
317        {
318            get
319            {
320                return GetXmlNodeString(_errorTitlePath);
321            }
322            set
323            {
324                SetXmlNodeString(_errorTitlePath, value);
325            }
326        }
327
328        /// <summary>
329        /// Error message box text
330        /// </summary>
331        public string Error
332        {
333            get
334            {
335                return GetXmlNodeString(_errorPath);
336            }
337            set
338            {
339                SetXmlNodeString(_errorPath, value);
340            }
341        }
342
343        public string PromptTitle
344        {
345            get
346            {
347                return GetXmlNodeString(_promptTitlePath);
348            }
349            set
350            {
351                SetXmlNodeString(_promptTitlePath, value);
352            }
353        }
354
355        public string Prompt
356        {
357            get
358            {
359                return GetXmlNodeString(_promptPath);
360            }
361            set
362            {
363                SetXmlNodeString(_promptPath, value);
364            }
365        }
366
367        /// <summary>
368        /// Formula 1
369        /// </summary>
370        protected string Formula1Internal
371        {
372            get
373            {
374                return GetXmlNodeString(_formula1Path);
375            }
376        }
377
378        /// <summary>
379        /// Formula 2
380        /// </summary>
381        protected string Formula2Internal
382        {
383            get
384            {
385                return GetXmlNodeString(_formula2Path);
386            }
387        }
388
389        #endregion
390
391        protected void SetValue<T>(Nullable<T> val, string path)
392            where T : struct
393        {
394            if (!val.HasValue)
395            {
396                DeleteNode(path);
397            }
398            var stringValue = val.Value.ToString().Replace(',', '.');
399            SetXmlNodeString(path, stringValue);
400        }
401    }
402}
Note: See TracBrowser for help on using the repository browser.