aodl /AODL/Document/SpreadsheetDocuments/SpreadsheetDocument.cs

Language C# Lines 580
MD5 Hash 59c080eb844938a4845caae4b52af316
Repository https://bitbucket.org/chrisc/aodl View Raw File
  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
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
 * 
 * Copyright 2008 Sun Microsystems, Inc. All rights reserved.
 * 
 * Use is subject to license terms.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy
 * of the License at http://www.apache.org/licenses/LICENSE-2.0. You can also
 * obtain a copy of the License at http://odftoolkit.org/docs/license.txt
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * 
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 ************************************************************************/

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
using System.Xml.Linq;
using AODL.Document.Content;
using AODL.Document.Content.Draw;
using AODL.Document.Content.EmbedObjects;
using AODL.Document.Content.Tables;
using AODL.Document.Custom;
using AODL.Document.Exceptions;
using AODL.Document.Export;
using AODL.Document.Import;
using AODL.Document.Import.OpenDocument;
using AODL.Document.Import.OpenDocument.NodeProcessors;
using AODL.Document.Styles;
using AODL.Document.TextDocuments;

namespace AODL.Document.SpreadsheetDocuments
{
    /// <summary>
    /// The SpreadsheetDocument class represent an OpenDocument
    /// spreadsheet document.
    /// </summary>
    public class SpreadsheetDocument : IDocument, IDisposable
    {
        private readonly IList<Graphic> _graphics;
        private bool _isLoadedFile;
        private const string _mimeTyp = "application/vnd.oasis.opendocument.spreadsheet";
        private int _tableCount;
        private readonly CustomFileCollection _customFiles;
        private XDocument _xmldoc;

        private IImporter _importer;

        private readonly StyleFactory m_styleFactory;

        /// <summary>
        /// Initializes a new instance of the <see cref="SpreadsheetDocument"/> class.
        /// </summary>
        public SpreadsheetDocument()
        {
            TableCollection = new TableCollection();
            Styles = new StyleCollection();
            m_styleFactory = new StyleFactory(this);
            CommonStyles = new StyleCollection();
            Content = new ContentCollection();
            _graphics = new List<Graphic>();
            FontList = new List<string>();
            EmbedObjects = new List<EmbedObject>();
            TableCollection.Inserted += TableCollection_Inserted;
            TableCollection.Removed += TableCollection_Removed;
            Content.Inserted += Content_Inserted;
            Content.Removed += Content_Removed;

            _customFiles = new CustomFileCollection();
            _customFiles.Clearing += CustomFiles_Clearing;
            _customFiles.Inserting += CustomFiles_Inserting;
            _customFiles.Removing += CustomFiles_Removing;
        }

        /// <summary>
        /// Gets the table count.
        /// </summary>
        /// <value>The table count.</value>
        public int TableCount
        {
            get { return _tableCount; }
        }

        /// <summary>
        /// Gets or sets the table collection.
        /// </summary>
        /// <value>The table collection.</value>
        public TableCollection TableCollection { get; set; }

        /// <summary>
        /// Gets or sets the document styes.
        /// </summary>
        /// <value>The document styes.</value>
        public DocumentStyles DocumentStyles { get; set; }

        /// <summary>
        /// Gets or sets the document setting.
        /// </summary>
        /// <value>The document setting.</value>
        public DocumentSetting DocumentSetting { get; set; }

        /// <summary>
        /// Gets or sets the document manifest.
        /// </summary>
        /// <value>The document manifest.</value>
        public DocumentManifest DocumentManifest { get; set; }

        /// <summary>
        /// Gets the MIME typ.
        /// </summary>
        /// <value>The MIME typ.</value>
        public string MimeTyp
        {
            get { return _mimeTyp; }
        }

        #region IDocument Members

        public IImporter Importer
        {
            get { return _importer; }
        }

        public StyleFactory StyleFactory
        {
            get { return m_styleFactory; }
        }

        /// <summary>
        /// The xml document the spreadsheet document based on.
        /// </summary>
        public XDocument XmlDoc
        {
            get { return _xmldoc; }
            set { _xmldoc = value; }
        }

        /// <summary>
        /// If this file was loaded
        /// </summary>
        /// <value></value>
        public bool IsLoadedFile
        {
            get { return _isLoadedFile; }
        }

        /// <summary>
        /// The font list
        /// </summary>
        /// <value></value>
        public IList<string> FontList { get; set; }

        /// <summary>
        /// Collection of local styles used with this document.
        /// </summary>
        /// <value></value>
        public StyleCollection Styles { get; set; }

        /// <summary>
        /// Collection of common styles used with this document.
        /// </summary>
        /// <value></value>
        public StyleCollection CommonStyles { get; set; }

        /// <summary>
        /// Collection of contents used by this document.
        /// </summary>
        /// <value></value>
        public ContentCollection Content { get; set; }

        /// <summary>
        /// Collection of custom files to include in package
        /// </summary>
        public CustomFileCollection CustomFiles
        {
            get { return _customFiles; }
        }

        /// <summary>
        /// Gets or sets the document metadata.
        /// </summary>
        /// <value>The document metadata.</value>
        public DocumentMetadata DocumentMetadata { get; set; }

        /// <summary>
        /// Gets or sets the document configuration2.
        /// </summary>
        /// <value>The document configuration2.</value>
        public DocumentConfiguration2 DocumentConfigurations2 { get; set; }

        /// <summary>
        /// Gets or sets the document pictures.
        /// </summary>
        /// <value>The document pictures.</value>
        public DocumentPictureCollection DocumentPictures { get; set; }

        /// <summary>
        /// Gets or sets the document thumbnails.
        /// </summary>
        /// <value>The document thumbnails.</value>
        public DocumentPictureCollection DocumentThumbnails { get; set; }

        /// <summary>
        /// Gets the graphics.
        /// </summary>
        /// <value>The graphics.</value>
        public IList<Graphic> Graphics
        {
            get { return _graphics; }
        }

        /// <summary>
        /// Gets the embedobject.
        /// </summary>
        /// <value>The embedobject.</value>
        public IList<EmbedObject> EmbedObjects { get; set; }

        /// <summary>
        /// Save the document by using the passed IExporter
        /// with the passed file name.
        /// </summary>
        /// <param name="filename">The name of the new file.</param>
        /// <param name="exporter"></param>
        public void Save(string filename, IExporter exporter)
        {
            CreateContentBody();
            exporter.Export(this, filename);
        }

        /// <summary>
        /// Load the given file.
        /// </summary>
        /// <param name="file"></param>
        /// <param name="importer"></param>
        public void Load(string file, IImporter importer)
        {
            _importer = importer;
            _isLoadedFile = true;
            LoadBlankContent();

            if (_importer != null)
            {
                if (_importer.NeedNewOpenDocument)
                    New();
                _importer.Import(this, file);

                if (_importer.ImportError != null)
                    if (_importer.ImportError.Count > 0)
                        foreach (AODLWarning ob in _importer.ImportError)
                        {
                            if (ob.Message != null)
                                Console.WriteLine("Err: {0}", ob.Message);
                            if (ob.Node != null)
                            {
                                using (XmlWriter writer = XmlWriter.Create(Console.Out, new XmlWriterSettings { Indent = true }))
                                {
                                    ob.Node.WriteTo(writer);
                                }
                            }
                        }
            }
        }

        #endregion

        /// <summary>
        /// Create a new blank spreadsheet document.
        /// </summary>
        public void New()
        {
            LoadBlankContent();

            DocumentConfigurations2 = new DocumentConfiguration2();

            DocumentManifest = new DocumentManifest();
            DocumentManifest.New();

            DocumentMetadata = new DocumentMetadata(this);
            DocumentMetadata.New();

            DocumentPictures = new DocumentPictureCollection();

            DocumentSetting = new DocumentSetting();
            DocumentSetting.New();

            DocumentStyles = new DocumentStyles();
            DocumentStyles.New();
            ReadCommonStyles();

            DocumentThumbnails = new DocumentPictureCollection();
        }

        /// <summary>
        /// Reads the common styles.
        /// </summary>
        private void ReadCommonStyles()
        {
            OpenDocumentImporter odImporter = new OpenDocumentImporter(null) {Document = this};
            odImporter.ImportCommonStyles();

            LocalStyleProcessor lsp = new LocalStyleProcessor(this, true);
            lsp.ReadStyles();
        }

        /// <summary>
        /// Load a blank the spreadsheet content document.
        /// </summary>
        private void LoadBlankContent()
        {
            Assembly ass = Assembly.GetExecutingAssembly();
            Stream str = ass.GetManifestResourceStream("AODL.Resources.OD.spreadsheetcontent.xml");
            using (XmlReader reader = XmlReader.Create(str))
            {
                _xmldoc = XDocument.Load(reader);
            }
        }

        /// <summary>
        /// Tables the collection_ inserted.
        /// </summary>
        /// <param name="index">The index.</param>
        /// <param name="value">The value.</param>
        private void TableCollection_Inserted(int index, object value)
        {
            _tableCount++;
            if (!Content.Contains(value as IContent))
                Content.Add(value as IContent);
        }

        /// <summary>
        /// Tables the collection_ removed.
        /// </summary>
        /// <param name="index">The index.</param>
        /// <param name="value">The value.</param>
        private void TableCollection_Removed(int index, object value)
        {
            _tableCount--;
            if (Content.Contains(value as IContent))
                Content.Remove(value as IContent);
        }

        /// <summary>
        /// Content_s the inserted.
        /// </summary>
        /// <param name="index">The index.</param>
        /// <param name="value">The value.</param>
        private void Content_Inserted(int index, object value)
        {
            if (value is Table)
                if (!TableCollection.Contains((Table) value))
                    TableCollection.Add(value as Table);
        }

        /// <summary>
        /// Content_s the removed.
        /// </summary>
        /// <param name="index">The index.</param>
        /// <param name="value">The value.</param>
        private void Content_Removed(int index, object value)
        {
            if (value is Table)
                if (TableCollection.Contains((Table) value))
                    TableCollection.Remove(value as Table);
        }

        /// <summary>
        /// Creates the content body.
        /// </summary>
        private void CreateContentBody()
        {
            XElement nodeSpreadSheets = XmlDoc.Elements(Ns.Office + "document-content")
                .Elements(Ns.Office + "body")
                .Elements(Ns.Office + "spreadsheet").First();

            foreach (IContent iContent in Content)
            {
                //only table content
                if (iContent is Table)
                    nodeSpreadSheets.Add(((Table) iContent).BuildNode());
            }

            CreateLocalStyleContent();
            CreateCommonStyleContent();
        }

        /// <summary>
        /// Creates the content of the local style.
        /// </summary>
        private void CreateLocalStyleContent()
        {
            XElement nodeAutomaticStyles = XmlDoc.Elements(Ns.Office + "document-content")
                .Elements(Ns.Office + "automatic-styles").First();

            foreach (IStyle style in Styles.ToValueList())
                nodeAutomaticStyles.Add(style.Node);
        }

        /// <summary>
        /// Creates the content of the common style.
        /// </summary>
        private void CreateCommonStyleContent()
        {
            XElement nodeCommonStyles = DocumentStyles.Styles.Elements(Ns.Office + "document-styles")
                .Elements(Ns.Office + "styles").First();
            nodeCommonStyles.Value = "";

            foreach (IStyle style in CommonStyles.ToValueList())
            {
                nodeCommonStyles.Add(new XElement(style.Node));
            }

            //Remove styles node
            nodeCommonStyles = XmlDoc.Elements(Ns.Office + "document-content")
                .Elements(Ns.Office + "styles").FirstOrDefault();
            if (nodeCommonStyles != null)
                nodeCommonStyles.Remove();
        }

        public EmbedObject GetObjectByName(string objectName)
        {
            for (int i = 0; i < EmbedObjects.Count; i++)
            {
                if ((EmbedObjects[i]).ObjectName == objectName)

                    return (EmbedObject) EmbedObjects[i];
            }

            return null;
        }

        private void CustomFiles_Clearing()
        {
            XElement root = DocumentManifest.Manifest.Element(Ns.Manifest + "manifest");
            foreach (ICustomFile customFile in _customFiles)
            {
                IEnumerable<XElement> fileEntries =
                    root.Elements(Ns.Manifest + "file-entry").Where(
                        e =>
                        ((string)e.Attribute(Ns.Manifest + "media-type")).Equals(customFile.MediaType ?? string.Empty,
                                                                                  StringComparison.InvariantCulture) &&
                        ((string)e.Attribute(Ns.Manifest + "full-path")).Equals(customFile.FullPath,
                                                                                 StringComparison.InvariantCulture));
                foreach (XElement fileEntry in fileEntries)
                {
                    fileEntry.Remove();
                }
            }
        }

        private void CustomFiles_Inserting(int index, ICustomFile value)
        {
            XElement root = DocumentManifest.Manifest.Element(Ns.Manifest + "manifest");
            IEnumerable<XElement> fileEntries =
                root.Elements(Ns.Manifest + "file-entry").Where(
                    e =>
                    ((string)e.Attribute(Ns.Manifest + "media-type")).Equals(value.MediaType ?? string.Empty,
                                                                              StringComparison.InvariantCulture) &&
                    ((string)e.Attribute(Ns.Manifest + "full-path")).Equals(value.FullPath,
                                                                             StringComparison.InvariantCulture));
            if (fileEntries.Count() > 0)
                return;
            XElement fileEntry = new XElement(Ns.Manifest + "file-entry");
            fileEntry.SetAttributeValue(Ns.Manifest + "media-type", value.MediaType ?? string.Empty);
            fileEntry.SetAttributeValue(Ns.Manifest + "full-path", value.FullPath);
            root.Add(fileEntry);
        }

        private void CustomFiles_Removing(int index, ICustomFile value)
        {
            XElement root = DocumentManifest.Manifest.Element(Ns.Manifest + "manifest");
            IEnumerable<XElement> fileEntries =
                root.Elements(Ns.Manifest + "file-entry").Where(
                    e =>
                    ((string)e.Attribute(Ns.Manifest + "media-type")).Equals(value.MediaType ?? string.Empty,
                                                                              StringComparison.InvariantCulture) &&
                    ((string)e.Attribute(Ns.Manifest + "full-path")).Equals(value.FullPath,
                                                                             StringComparison.InvariantCulture));
            foreach (XElement fileEntry in fileEntries)
            {
                fileEntry.Remove();
            }
        }

        #region IDisposable Member

        private bool _disposed;

        /// <summary>
        /// Releases unmanaged resources and performs other cleanup operations before the
        /// is reclaimed by garbage collection.
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Disposes the specified disposing.
        /// </summary>
        /// <param name="disposing">if set to <c>true</c> [disposing].</param>
        private void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    //DeleteUnpackedFiles();
                }
            }
            _disposed = true;
        }

        /// <summary>
        /// Releases unmanaged resources and performs other cleanup operations before the
        /// <see cref="AODL.Document.TextDocuments.TextDocument"/> is reclaimed by garbage collection.
        /// </summary>
        ~SpreadsheetDocument()
        {
            Dispose();
        }

        #endregion
    }
}

/*
 * $Log: SpreadsheetDocument.cs,v $
 * Revision 1.3  2008/04/29 15:39:53  mt
 * new copyright header
 *
 * Revision 1.2  2008/02/08 07:12:20  larsbehr
 * - added initial chart support
 * - several bug fixes
 *
 * Revision 1.1  2007/02/25 08:58:47  larsbehr
 * initial checkin, import from Sourceforge.net to OpenOffice.org
 *
 * Revision 1.7  2007/02/04 22:52:57  larsbm
 * - fixed bug in resize algorithm for rows and cells
 * - extending IDocument, overload SaveTo to accept external exporter impl.
 * - initial version of AODL PDF exporter add on
 *
 * Revision 1.6  2006/02/21 19:34:55  larsbm
 * - Fixed Bug text that contains a xml tag will be imported  as UnknowText and not correct displayed if document is exported  as HTML.
 * - Fixed Bug [ 1436080 ] Common styles
 *
 * Revision 1.5  2006/02/06 19:27:23  larsbm
 * - fixed bug in spreadsheet document
 * - added smal OpenOfficeLib for document printing
 *
 * Revision 1.4  2006/02/05 20:03:32  larsbm
 * - Fixed several bugs
 * - clean up some messy code
 *
 * Revision 1.3  2006/02/02 21:55:59  larsbm
 * - Added Clone object support for many AODL object types
 * - New Importer implementation PlainTextImporter and CsvImporter
 * - New tests
 *
 * Revision 1.2  2006/01/29 18:52:14  larsbm
 * - Added support for common styles (style templates in OpenOffice)
 * - Draw TextBox import and export
 * - DrawTextBox html export
 *
 * Revision 1.1  2006/01/29 11:28:23  larsbm
 * - Changes for the new version. 1.2. see next changelog for details
 *
 */
Back to Top