Free cookie consent management tool by TermsFeed Policy Generator

source: branches/ExportSymbolicDataAnalysisSolutions/HeuristicLab.ExtLibs/HeuristicLab.EPPlus/3.1.3/EPPlus-3.1.3/OfficeProperties.cs @ 9931

Last change on this file since 9931 was 9580, checked in by sforsten, 11 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: 20.4 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 * Jan Källman                    Initial Release           2009-10-01
30 * Jan Källman                      Total rewrite               2010-03-01
31 * Jan Källman        License changed GPL-->LGPL  2011-12-27
32 *******************************************************************************/
33using System;
34using System.Xml;
35using System.IO;
36using System.IO.Packaging;
37using System.Globalization;
38
39namespace OfficeOpenXml
40{
41    /// <summary>
42    /// Provides access to the properties bag of the package
43    /// </summary>
44    public sealed class OfficeProperties : XmlHelper
45    {
46        #region Private Properties
47        private XmlDocument _xmlPropertiesCore;
48        private XmlDocument _xmlPropertiesExtended;
49        private XmlDocument _xmlPropertiesCustom;
50
51        private Uri _uriPropertiesCore = new Uri("/docProps/core.xml", UriKind.Relative);
52        private Uri _uriPropertiesExtended = new Uri("/docProps/app.xml", UriKind.Relative);
53        private Uri _uriPropertiesCustom = new Uri("/docProps/custom.xml", UriKind.Relative);
54
55        XmlHelper _coreHelper;
56        XmlHelper _extendedHelper;
57        XmlHelper _customHelper;
58        private ExcelPackage _package;
59        #endregion
60
61        #region ExcelProperties Constructor
62        /// <summary>
63        /// Provides access to all the office document properties.
64        /// </summary>
65        /// <param name="package"></param>
66        /// <param name="ns"></param>
67        internal OfficeProperties(ExcelPackage package, XmlNamespaceManager ns) :
68            base(ns)
69        {
70            _package = package;
71
72            _coreHelper = XmlHelperFactory.Create(ns, CorePropertiesXml.SelectSingleNode("cp:coreProperties", NameSpaceManager));
73            _extendedHelper = XmlHelperFactory.Create(ns, ExtendedPropertiesXml);
74            _customHelper = XmlHelperFactory.Create(ns, CustomPropertiesXml);
75
76        }
77        #endregion
78        #region CorePropertiesXml
79        /// <summary>
80        /// Provides access to the XML document that holds all the code
81        /// document properties.
82        /// </summary>
83        public XmlDocument CorePropertiesXml
84        {
85            get
86            {
87                if (_xmlPropertiesCore == null)
88                {
89                    string xml = string.Format("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?><cp:coreProperties xmlns:cp=\"{0}\" xmlns:dc=\"{1}\" xmlns:dcterms=\"{2}\" xmlns:dcmitype=\"{3}\" xmlns:xsi=\"{4}\"></cp:coreProperties>",
90                        ExcelPackage.schemaCore,
91                        ExcelPackage.schemaDc,
92                        ExcelPackage.schemaDcTerms,
93                        ExcelPackage.schemaDcmiType,
94                        ExcelPackage.schemaXsi);
95
96                    _xmlPropertiesCore = GetXmlDocument(xml, _uriPropertiesCore, @"application/vnd.openxmlformats-package.core-properties+xml", @"http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties");
97                }
98                return (_xmlPropertiesCore);
99            }
100        }
101
102        private XmlDocument GetXmlDocument(string startXml, Uri uri, string contentType, string relationship)
103        {
104            XmlDocument xmlDoc;
105            if (_package.Package.PartExists(uri))
106                xmlDoc = _package.GetXmlFromUri(uri);
107            else
108            {
109                xmlDoc = new XmlDocument();
110                xmlDoc.LoadXml(startXml);
111
112                // Create a the part and add to the package
113                PackagePart part = _package.Package.CreatePart(uri, contentType);
114
115                // Save it to the package
116                StreamWriter stream = new StreamWriter(part.GetStream(FileMode.Create, FileAccess.Write));
117                xmlDoc.Save(stream);
118                stream.Close();
119                _package.Package.Flush();
120
121                // create the relationship between the workbook and the new shared strings part
122                _package.Package.CreateRelationship(PackUriHelper.GetRelativeUri(new Uri("/xl", UriKind.Relative), uri), TargetMode.Internal, relationship);
123                _package.Package.Flush();
124            }
125            return xmlDoc;
126        }
127        #endregion
128        #region Core Properties
129        const string TitlePath = "dc:title";
130        /// <summary>
131        /// Gets/sets the title property of the document (core property)
132        /// </summary>
133        public string Title
134        {
135            get { return _coreHelper.GetXmlNodeString(TitlePath); }
136            set { _coreHelper.SetXmlNodeString(TitlePath, value); }
137        }
138
139        const string SubjectPath = "dc:subject";
140        /// <summary>
141        /// Gets/sets the subject property of the document (core property)
142        /// </summary>
143        public string Subject
144        {
145            get { return _coreHelper.GetXmlNodeString(SubjectPath); }
146            set { _coreHelper.SetXmlNodeString(SubjectPath, value); }
147        }
148
149        const string AuthorPath = "dc:creator";
150        /// <summary>
151        /// Gets/sets the author property of the document (core property)
152        /// </summary>
153        public string Author
154        {
155            get { return _coreHelper.GetXmlNodeString(AuthorPath); }
156            set { _coreHelper.SetXmlNodeString(AuthorPath, value); }
157        }
158
159        const string CommentsPath = "dc:description";
160        /// <summary>
161        /// Gets/sets the comments property of the document (core property)
162        /// </summary>
163        public string Comments
164        {
165            get { return _coreHelper.GetXmlNodeString(CommentsPath); }
166            set { _coreHelper.SetXmlNodeString(CommentsPath, value); }
167        }
168
169        const string KeywordsPath = "cp:keywords";
170        /// <summary>
171        /// Gets/sets the keywords property of the document (core property)
172        /// </summary>
173        public string Keywords
174        {
175            get { return _coreHelper.GetXmlNodeString(KeywordsPath); }
176            set { _coreHelper.SetXmlNodeString(KeywordsPath, value); }
177        }
178
179        const string LastModifiedByPath = "cp:lastModifiedBy";
180        /// <summary>
181        /// Gets/sets the lastModifiedBy property of the document (core property)
182        /// </summary>
183        public string LastModifiedBy
184        {
185            get { return _coreHelper.GetXmlNodeString(LastModifiedByPath); }
186            set { _coreHelper.SetXmlNodeString(LastModifiedByPath, value); }
187        }
188
189        const string LastPrintedPath = "cp:lastPrinted";
190        /// <summary>
191        /// Gets/sets the lastPrinted property of the document (core property)
192        /// </summary>
193        public string LastPrinted
194        {
195            get { return _coreHelper.GetXmlNodeString(LastPrintedPath); }
196            set { _coreHelper.SetXmlNodeString(LastPrintedPath, value); }
197        }
198
199        const string CategoryPath = "cp:category";
200        /// <summary>
201        /// Gets/sets the category property of the document (core property)
202        /// </summary>
203        public string Category
204        {
205            get { return _coreHelper.GetXmlNodeString(CategoryPath); }
206            set { _coreHelper.SetXmlNodeString(CategoryPath, value); }
207        }
208
209        const string ContentStatusPath = "cp:contentStatus";
210        /// <summary>
211        /// Gets/sets the status property of the document (core property)
212        /// </summary>
213        public string Status
214        {
215            get { return _coreHelper.GetXmlNodeString(ContentStatusPath); }
216            set { _coreHelper.SetXmlNodeString(ContentStatusPath, value); }
217        }
218        #endregion
219
220        #region Extended Properties
221        #region ExtendedPropertiesXml
222        /// <summary>
223        /// Provides access to the XML document that holds the extended properties of the document (app.xml)
224        /// </summary>
225        public XmlDocument ExtendedPropertiesXml
226        {
227            get
228            {
229                if (_xmlPropertiesExtended == null)
230                {
231                    _xmlPropertiesExtended = GetXmlDocument(string.Format("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?><Properties xmlns:vt=\"{0}\" xmlns=\"{1}\"></Properties>",
232                            ExcelPackage.schemaVt,
233                            ExcelPackage.schemaExtended),
234                        _uriPropertiesExtended,
235                        @"application/vnd.openxmlformats-officedocument.extended-properties+xml",
236                        @"http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties");
237                }
238                return (_xmlPropertiesExtended);
239            }
240        }
241        #endregion
242
243        const string ApplicationPath = "xp:Properties/xp:Application";
244        /// <summary>
245        /// Gets the Application property of the document (extended property)
246        /// </summary>
247        public string Application
248        {
249            get { return _extendedHelper.GetXmlNodeString(ApplicationPath); }
250        }
251
252        const string HyperlinkBasePath = "xp:Properties/xp:HyperlinkBase";
253        /// <summary>
254        /// Gets/sets the HyperlinkBase property of the document (extended property)
255        /// </summary>
256        public Uri HyperlinkBase
257        {
258            get { return new Uri(_extendedHelper.GetXmlNodeString(HyperlinkBasePath), UriKind.Absolute); }
259            set { _extendedHelper.SetXmlNodeString(HyperlinkBasePath, value.AbsoluteUri); }
260        }
261
262        const string AppVersionPath = "xp:Properties/xp:AppVersion";
263        /// <summary>
264        /// Gets the AppVersion property of the document (extended property)
265        /// </summary>
266        public string AppVersion
267        {
268            get { return _extendedHelper.GetXmlNodeString(AppVersionPath); }
269        }
270        const string CompanyPath = "xp:Properties/xp:Company";
271
272        /// <summary>
273        /// Gets/sets the Company property of the document (extended property)
274        /// </summary>
275        public string Company
276        {
277            get { return _extendedHelper.GetXmlNodeString(CompanyPath); }
278            set { _extendedHelper.SetXmlNodeString(CompanyPath, value); }
279        }
280
281        const string ManagerPath = "xp:Properties/xp:Manager";
282        /// <summary>
283        /// Gets/sets the Manager property of the document (extended property)
284        /// </summary>
285        public string Manager
286        {
287            get { return _extendedHelper.GetXmlNodeString(ManagerPath); }
288            set { _extendedHelper.SetXmlNodeString(ManagerPath, value); }
289        }
290
291        #region Get and Set Extended Properties
292        private string GetExtendedPropertyValue(string propertyName)
293        {
294            string retValue = null;
295            string searchString = string.Format("xp:Properties/xp:{0}", propertyName);
296            XmlNode node = ExtendedPropertiesXml.SelectSingleNode(searchString, NameSpaceManager);
297            if (node != null)
298            {
299                retValue = node.InnerText;
300            }
301            return retValue;
302        }
303        #endregion
304        #endregion
305
306        #region Custom Properties
307
308        #region CustomPropertiesXml
309        /// <summary>
310        /// Provides access to the XML document which holds the document's custom properties
311        /// </summary>
312        public XmlDocument CustomPropertiesXml
313        {
314            get
315            {
316                if (_xmlPropertiesCustom == null)
317                {
318                    _xmlPropertiesCustom = GetXmlDocument(string.Format("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?><Properties xmlns:vt=\"{0}\" xmlns=\"{1}\"></Properties>",
319                            ExcelPackage.schemaVt,
320                            ExcelPackage.schemaCustom),
321                         _uriPropertiesCustom,
322                         @"application/vnd.openxmlformats-officedocument.custom-properties+xml",
323                         @"http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties");
324                }
325                return (_xmlPropertiesCustom);
326            }
327        }
328        #endregion
329
330        #region Get and Set Custom Properties
331        /// <summary>
332        /// Gets the value of a custom property
333        /// </summary>
334        /// <param name="propertyName">The name of the property</param>
335        /// <returns>The current value of the property</returns>
336        public object GetCustomPropertyValue(string propertyName)
337        {
338            string searchString = string.Format("ctp:Properties/ctp:property[@name='{0}']", propertyName);
339            XmlElement node = CustomPropertiesXml.SelectSingleNode(searchString, NameSpaceManager) as XmlElement;
340            if (node != null)
341            {
342                string value = node.LastChild.InnerText;
343                switch (node.LastChild.LocalName)
344                {
345                    case "filetime":
346                        DateTime dt;
347                        if (DateTime.TryParse(value, out dt))
348                        {
349                            return dt;
350                        }
351                        else
352                        {
353                            return null;
354                        }
355                    case "i4":
356                        int i;
357                        if (int.TryParse(value, out i))
358                        {
359                            return i;
360                        }
361                        else
362                        {
363                            return null;
364                        }
365                    case "r8":
366                        double d;
367                        if (double.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out d))
368                        {
369                            return d;
370                        }
371                        else
372                        {
373                            return null;
374                        }
375                    case "bool":
376                        if (value == "true")
377                        {
378                            return true;
379                        }
380                        else if (value == "false")
381                        {
382                            return false;
383                        }
384                        else
385                        {
386                            return null;
387                        }
388                    default:
389                        return value;
390                }
391            }
392            else
393            {
394                return null;
395            }
396        }
397
398        /// <summary>
399        /// Allows you to set the value of a current custom property or create your own custom property. 
400        /// </summary>
401        /// <param name="propertyName">The name of the property</param>
402        /// <param name="value">The value of the property</param>
403        public void SetCustomPropertyValue(string propertyName, object value)
404        {
405            XmlNode allProps = CustomPropertiesXml.SelectSingleNode(@"ctp:Properties", NameSpaceManager);
406
407            var prop = string.Format("ctp:Properties/ctp:property[@name='{0}']", propertyName);
408            XmlElement node = CustomPropertiesXml.SelectSingleNode(prop, NameSpaceManager) as XmlElement;
409            if (node == null)
410            {
411                int pid;
412                var MaxNode = CustomPropertiesXml.SelectSingleNode("ctp:Properties/ctp:property[not(@pid <= preceding-sibling::ctp:property/@pid) and not(@pid <= following-sibling::ctp:property/@pid)]", NameSpaceManager);
413                if (MaxNode == null)
414                {
415                    pid = 2;
416                }
417                else
418                {
419                    if (!int.TryParse(MaxNode.Attributes["pid"].Value, out pid))
420                    {
421                        pid = 2;
422                    }
423                    pid++;
424                }
425                node = CustomPropertiesXml.CreateElement("property", ExcelPackage.schemaCustom);
426                node.SetAttribute("fmtid", "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}");
427                node.SetAttribute("pid", pid.ToString());  // custom property pid
428                node.SetAttribute("name", propertyName);
429
430                allProps.AppendChild(node);
431            }
432            else
433            {
434                while (node.ChildNodes.Count > 0) node.RemoveChild(node.ChildNodes[0]);
435            }
436            XmlElement valueElem;
437            if (value is bool)
438            {
439                valueElem = CustomPropertiesXml.CreateElement("vt", "bool", ExcelPackage.schemaVt);
440                valueElem.InnerText = value.ToString().ToLower();
441            }
442            else if (value is DateTime)
443            {
444                valueElem = CustomPropertiesXml.CreateElement("vt", "filetime", ExcelPackage.schemaVt);
445                valueElem.InnerText = ((DateTime)value).AddHours(-1).ToString("yyyy-MM-ddTHH:mm:ssZ");
446            }
447            else if (value is short || value is int)
448            {
449                valueElem = CustomPropertiesXml.CreateElement("vt", "i4", ExcelPackage.schemaVt);
450                valueElem.InnerText = value.ToString();
451            }
452            else if (value is double || value is decimal || value is float || value is long)
453            {
454                valueElem = CustomPropertiesXml.CreateElement("vt", "r8", ExcelPackage.schemaVt);
455                if (value is double)
456                {
457                    valueElem.InnerText = ((double)value).ToString(CultureInfo.InvariantCulture);
458                }
459                else if (value is float)
460                {
461                    valueElem.InnerText = ((float)value).ToString(CultureInfo.InvariantCulture);
462                }
463                else if (value is decimal)
464                {
465                    valueElem.InnerText = ((decimal)value).ToString(CultureInfo.InvariantCulture);
466                }
467                else
468                {
469                    valueElem.InnerText = value.ToString();
470                }
471            }
472            else
473            {
474                valueElem = CustomPropertiesXml.CreateElement("vt", "lpwstr", ExcelPackage.schemaVt);
475                valueElem.InnerText = value.ToString();
476            }
477            node.AppendChild(valueElem);
478        }
479        #endregion
480        #endregion
481
482        #region Save
483        /// <summary>
484        /// Saves the document properties back to the package.
485        /// </summary>
486        internal void Save()
487        {
488            if (_xmlPropertiesCore != null)
489            {
490                _package.SavePart(_uriPropertiesCore, _xmlPropertiesCore);
491            }
492            if (_xmlPropertiesExtended != null)
493            {
494                _package.SavePart(_uriPropertiesExtended, _xmlPropertiesExtended);
495            }
496            if (_xmlPropertiesCustom != null)
497            {
498                _package.SavePart(_uriPropertiesCustom, _xmlPropertiesCustom);
499            }
500
501        }
502        #endregion
503
504    }
505}
Note: See TracBrowser for help on using the repository browser.