/*******************************************************************************
* You may amend and distribute as you like, but don't remove this header!
*
* EPPlus provides server-side generation of Excel 2007/2010 spreadsheets.
* See http://www.codeplex.com/EPPlus for details.
*
* Copyright (C) 2011 Jan Källman
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* The GNU Lesser General Public License can be viewed at http://www.opensource.org/licenses/lgpl-license.php
* If you unfamiliar with this license or have questions about it, here is an http://www.gnu.org/licenses/gpl-faq.html
*
* All code and executables are provided "as is" with no warranty either express or implied.
* The author accepts no liability for any damage or loss of business that this product may cause.
*
* Code change notes:
*
* Author Change Date
* ******************************************************************************
* Jan Källman Initial Release 2009-10-01
* Jan Källman License changed GPL-->LGPL 2011-12-27
*******************************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography.Xml;
using System.Text;
using System.Xml;
using System.IO;
using System.Linq;
using OfficeOpenXml.Style;
using OfficeOpenXml.Drawing;
using OfficeOpenXml.Drawing.Chart;
using OfficeOpenXml.Style.XmlAccess;
using OfficeOpenXml.Drawing.Vml;
using OfficeOpenXml.Packaging.Ionic.Zlib;
using OfficeOpenXml.Utils;
using OfficeOpenXml.VBA;
namespace OfficeOpenXml
{
///
/// The collection of worksheets for the workbook
///
public class ExcelWorksheets : XmlHelper, IEnumerable, IDisposable
{
#region Private Properties
private ExcelPackage _pck;
private Dictionary _worksheets;
private XmlNamespaceManager _namespaceManager;
#endregion
#region ExcelWorksheets Constructor
internal ExcelWorksheets(ExcelPackage pck, XmlNamespaceManager nsm, XmlNode topNode) :
base(nsm, topNode)
{
_pck = pck;
_namespaceManager = nsm;
_worksheets = new Dictionary();
int positionID = 1;
foreach (XmlNode sheetNode in topNode.ChildNodes)
{
if (sheetNode.NodeType == XmlNodeType.Element)
{
string name = sheetNode.Attributes["name"].Value;
//Get the relationship id
string relId = sheetNode.Attributes["r:id"].Value;
int sheetID = Convert.ToInt32(sheetNode.Attributes["sheetId"].Value);
//Hidden property
eWorkSheetHidden hidden = eWorkSheetHidden.Visible;
XmlNode attr = sheetNode.Attributes["state"];
if (attr != null)
hidden = TranslateHidden(attr.Value);
var sheetRelation = pck.Workbook.Part.GetRelationship(relId);
Uri uriWorksheet = UriHelper.ResolvePartUri(pck.Workbook.WorkbookUri, sheetRelation.TargetUri);
//add the worksheet
if (sheetRelation.RelationshipType.EndsWith("chartsheet"))
{
_worksheets.Add(positionID, new ExcelChartsheet(_namespaceManager, _pck, relId, uriWorksheet, name, sheetID, positionID, hidden));
}
else
{
_worksheets.Add(positionID, new ExcelWorksheet(_namespaceManager, _pck, relId, uriWorksheet, name, sheetID, positionID, hidden));
}
positionID++;
}
}
}
private eWorkSheetHidden TranslateHidden(string value)
{
switch (value)
{
case "hidden":
return eWorkSheetHidden.Hidden;
case "veryHidden":
return eWorkSheetHidden.VeryHidden;
default:
return eWorkSheetHidden.Visible;
}
}
#endregion
#region ExcelWorksheets Public Properties
///
/// Returns the number of worksheets in the workbook
///
public int Count
{
get { return (_worksheets.Count); }
}
#endregion
private const string ERR_DUP_WORKSHEET = "A worksheet with this name already exists in the workbook";
internal const string WORKSHEET_CONTENTTYPE = @"application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml";
internal const string CHARTSHEET_CONTENTTYPE = @"application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml";
#region ExcelWorksheets Public Methods
///
/// Foreach support
///
/// An enumerator
public IEnumerator GetEnumerator()
{
return (_worksheets.Values.GetEnumerator());
}
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
return (_worksheets.Values.GetEnumerator());
}
#endregion
#region Add Worksheet
///
/// Adds a new blank worksheet.
///
/// The name of the workbook
public ExcelWorksheet Add(string Name)
{
ExcelWorksheet worksheet = AddSheet(Name,false, null);
return worksheet;
}
private ExcelWorksheet AddSheet(string Name, bool isChart, eChartType? chartType)
{
int sheetID;
Uri uriWorksheet;
lock (_worksheets)
{
Name = ValidateFixSheetName(Name);
if (GetByName(Name) != null)
{
throw (new InvalidOperationException(ERR_DUP_WORKSHEET + " : " + Name));
}
GetSheetURI(ref Name, out sheetID, out uriWorksheet, isChart);
Packaging.ZipPackagePart worksheetPart = _pck.Package.CreatePart(uriWorksheet, isChart ? CHARTSHEET_CONTENTTYPE : WORKSHEET_CONTENTTYPE, _pck.Compression);
//Create the new, empty worksheet and save it to the package
StreamWriter streamWorksheet = new StreamWriter(worksheetPart.GetStream(FileMode.Create, FileAccess.Write));
XmlDocument worksheetXml = CreateNewWorksheet(isChart);
worksheetXml.Save(streamWorksheet);
_pck.Package.Flush();
string rel = CreateWorkbookRel(Name, sheetID, uriWorksheet, isChart);
int positionID = _worksheets.Count + 1;
ExcelWorksheet worksheet;
if (isChart)
{
worksheet = new ExcelChartsheet(_namespaceManager, _pck, rel, uriWorksheet, Name, sheetID, positionID, eWorkSheetHidden.Visible, (eChartType)chartType);
}
else
{
worksheet = new ExcelWorksheet(_namespaceManager, _pck, rel, uriWorksheet, Name, sheetID, positionID, eWorkSheetHidden.Visible);
}
_worksheets.Add(positionID, worksheet);
#if !MONO
if (_pck.Workbook.VbaProject != null)
{
var name = _pck.Workbook.VbaProject.GetModuleNameFromWorksheet(worksheet);
_pck.Workbook.VbaProject.Modules.Add(new ExcelVBAModule(worksheet.CodeNameChange) { Name = name, Code = "", Attributes = _pck.Workbook.VbaProject.GetDocumentAttributes(Name, "0{00020820-0000-0000-C000-000000000046}"), Type = eModuleType.Document, HelpContext = 0 });
worksheet.CodeModuleName = name;
}
#endif
return worksheet;
}
}
///
/// Adds a copy of a worksheet
///
/// The name of the workbook
/// The worksheet to be copied
public ExcelWorksheet Add(string Name, ExcelWorksheet Copy)
{
lock (_worksheets)
{
int sheetID;
Uri uriWorksheet;
if (Copy is ExcelChartsheet)
{
throw (new ArgumentException("Can not copy a chartsheet"));
}
if (GetByName(Name) != null)
{
throw (new InvalidOperationException(ERR_DUP_WORKSHEET));
}
GetSheetURI(ref Name, out sheetID, out uriWorksheet, false);
//Create a copy of the worksheet XML
Packaging.ZipPackagePart worksheetPart = _pck.Package.CreatePart(uriWorksheet, WORKSHEET_CONTENTTYPE, _pck.Compression);
StreamWriter streamWorksheet = new StreamWriter(worksheetPart.GetStream(FileMode.Create, FileAccess.Write));
XmlDocument worksheetXml = new XmlDocument();
worksheetXml.LoadXml(Copy.WorksheetXml.OuterXml);
worksheetXml.Save(streamWorksheet);
//streamWorksheet.Close();
_pck.Package.Flush();
//Create a relation to the workbook
string relID = CreateWorkbookRel(Name, sheetID, uriWorksheet, false);
ExcelWorksheet added = new ExcelWorksheet(_namespaceManager, _pck, relID, uriWorksheet, Name, sheetID, _worksheets.Count + 1, eWorkSheetHidden.Visible);
//Copy comments
if (Copy.Comments.Count > 0)
{
CopyComment(Copy, added);
}
else if (Copy.VmlDrawingsComments.Count > 0) //Vml drawings are copied as part of the comments.
{
CopyVmlDrawing(Copy, added);
}
//Copy HeaderFooter
CopyHeaderFooterPictures(Copy, added);
//Copy all relationships
//CopyRelationShips(Copy, added);
if (Copy.Drawings.Count > 0)
{
CopyDrawing(Copy, added);
}
if (Copy.Tables.Count > 0)
{
CopyTable(Copy, added);
}
if (Copy.PivotTables.Count > 0)
{
CopyPivotTable(Copy, added);
}
if (Copy.Names.Count > 0)
{
CopySheetNames(Copy, added);
}
//Copy all cells
CloneCells(Copy, added);
//Copy the VBA code
#if !MONO
if (_pck.Workbook.VbaProject != null)
{
var name = _pck.Workbook.VbaProject.GetModuleNameFromWorksheet(added);
_pck.Workbook.VbaProject.Modules.Add(new ExcelVBAModule(added.CodeNameChange) { Name = name, Code = Copy.CodeModule.Code, Attributes = _pck.Workbook.VbaProject.GetDocumentAttributes(Name, "0{00020820-0000-0000-C000-000000000046}"), Type = eModuleType.Document, HelpContext = 0 });
Copy.CodeModuleName = name;
}
#endif
_worksheets.Add(_worksheets.Count + 1, added);
//Remove any relation to printersettings.
XmlNode pageSetup = added.WorksheetXml.SelectSingleNode("//d:pageSetup", _namespaceManager);
if (pageSetup != null)
{
XmlAttribute attr = (XmlAttribute)pageSetup.Attributes.GetNamedItem("id", ExcelPackage.schemaRelationships);
if (attr != null)
{
relID = attr.Value;
// first delete the attribute from the XML
pageSetup.Attributes.Remove(attr);
}
}
return added;
}
}
public ExcelChartsheet AddChart(string Name, eChartType chartType)
{
return (ExcelChartsheet)AddSheet(Name, true, chartType);
}
private void CopySheetNames(ExcelWorksheet Copy, ExcelWorksheet added)
{
foreach (var name in Copy.Names)
{
ExcelNamedRange newName;
if (!name.IsName)
{
if (name.WorkSheet == Copy.Name)
{
newName = added.Names.Add(name.Name, added.Cells[name.FirstAddress]);
}
else
{
newName = added.Names.Add(name.Name, added.Workbook.Worksheets[name.WorkSheet].Cells[name.FirstAddress]);
}
}
else if (!string.IsNullOrEmpty(name.NameFormula))
{
newName=added.Names.AddFormula(name.Name, name.Formula);
}
else
{
newName=added.Names.AddValue(name.Name, name.Value);
}
newName.NameComment = name.NameComment;
}
}
private void CopyTable(ExcelWorksheet Copy, ExcelWorksheet added)
{
string prevName = "";
//First copy the table XML
foreach (var tbl in Copy.Tables)
{
string xml=tbl.TableXml.OuterXml;
int Id = _pck.Workbook._nextTableID++;
string name;
if (prevName == "")
{
name = Copy.Tables.GetNewTableName();
}
else
{
int ix = int.Parse(prevName.Substring(5)) + 1;
name = string.Format("Table{0}", ix);
while (_pck.Workbook.ExistsPivotTableName(name))
{
name = string.Format("Table{0}", ++ix);
}
}
prevName = name;
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
xmlDoc.SelectSingleNode("//d:table/@id", tbl.NameSpaceManager).Value = Id.ToString();
xmlDoc.SelectSingleNode("//d:table/@name", tbl.NameSpaceManager).Value = name;
xmlDoc.SelectSingleNode("//d:table/@displayName", tbl.NameSpaceManager).Value = name;
xml = xmlDoc.OuterXml;
var uriTbl = new Uri(string.Format("/xl/tables/table{0}.xml", Id), UriKind.Relative);
var part = _pck.Package.CreatePart(uriTbl, "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml", _pck.Compression);
StreamWriter streamTbl = new StreamWriter(part.GetStream(FileMode.Create, FileAccess.Write));
streamTbl.Write(xml);
//streamTbl.Close();
streamTbl.Flush();
//create the relationship and add the ID to the worksheet xml.
var rel = added.Part.CreateRelationship(UriHelper.GetRelativeUri(added.WorksheetUri,uriTbl), Packaging.TargetMode.Internal, ExcelPackage.schemaRelationships + "/table");
if (tbl.RelationshipID == null)
{
var topNode = added.WorksheetXml.SelectSingleNode("//d:tableParts", tbl.NameSpaceManager);
if (topNode == null)
{
added.CreateNode("d:tableParts");
topNode = added.WorksheetXml.SelectSingleNode("//d:tableParts", tbl.NameSpaceManager);
}
XmlElement elem = added.WorksheetXml.CreateElement("tablePart", ExcelPackage.schemaMain);
topNode.AppendChild(elem);
elem.SetAttribute("id",ExcelPackage.schemaRelationships, rel.Id);
}
else
{
XmlAttribute relAtt;
relAtt = added.WorksheetXml.SelectSingleNode(string.Format("//d:tableParts/d:tablePart/@r:id[.='{0}']", tbl.RelationshipID), tbl.NameSpaceManager) as XmlAttribute;
relAtt.Value = rel.Id;
}
}
}
private void CopyPivotTable(ExcelWorksheet Copy, ExcelWorksheet added)
{
string prevName = "";
foreach (var tbl in Copy.PivotTables)
{
string xml = tbl.PivotTableXml.OuterXml;
int Id = _pck.Workbook._nextPivotTableID++;
string name;
if (prevName == "")
{
name = Copy.PivotTables.GetNewTableName();
}
else
{
int ix=int.Parse(prevName.Substring(10))+1;
name = string.Format("PivotTable{0}", ix);
while (_pck.Workbook.ExistsPivotTableName(name))
{
name = string.Format("PivotTable{0}", ++ix);
}
}
prevName=name;
XmlDocument xmlDoc = new XmlDocument();
//TODO: Fix save pivottable here
//Copy.Save(); //Save the worksheet first
xmlDoc.LoadXml(xml);
//xmlDoc.SelectSingleNode("//d:table/@id", tbl.NameSpaceManager).Value = Id.ToString();
xmlDoc.SelectSingleNode("//d:pivotTableDefinition/@name", tbl.NameSpaceManager).Value = name;
xml = xmlDoc.OuterXml;
var uriTbl = new Uri(string.Format("/xl/pivotTables/pivotTable{0}.xml", Id), UriKind.Relative);
var partTbl = _pck.Package.CreatePart(uriTbl, ExcelPackage.schemaPivotTable , _pck.Compression);
StreamWriter streamTbl = new StreamWriter(partTbl.GetStream(FileMode.Create, FileAccess.Write));
streamTbl.Write(xml);
//streamTbl.Close();
streamTbl.Flush();
xml = tbl.CacheDefinition.CacheDefinitionXml.OuterXml;
var uriCd = new Uri(string.Format("/xl/pivotCache/pivotcachedefinition{0}.xml", Id), UriKind.Relative);
while (_pck.Package.PartExists(uriCd))
{
uriCd = new Uri(string.Format("/xl/pivotCache/pivotcachedefinition{0}.xml", ++Id), UriKind.Relative);
}
var partCd = _pck.Package.CreatePart(uriCd, ExcelPackage.schemaPivotCacheDefinition, _pck.Compression);
StreamWriter streamCd = new StreamWriter(partCd.GetStream(FileMode.Create, FileAccess.Write));
streamCd.Write(xml);
streamCd.Flush();
xml = "";
var uriRec = new Uri(string.Format("/xl/pivotCache/pivotrecords{0}.xml", Id), UriKind.Relative);
while (_pck.Package.PartExists(uriRec))
{
uriRec = new Uri(string.Format("/xl/pivotCache/pivotrecords{0}.xml", ++Id), UriKind.Relative);
}
var partRec = _pck.Package.CreatePart(uriRec, ExcelPackage.schemaPivotCacheRecords, _pck.Compression);
StreamWriter streamRec = new StreamWriter(partRec.GetStream(FileMode.Create, FileAccess.Write));
streamRec.Write(xml);
streamRec.Flush();
//create the relationship and add the ID to the worksheet xml.
added.Part.CreateRelationship(UriHelper.ResolvePartUri(added.WorksheetUri, uriTbl), Packaging.TargetMode.Internal, ExcelPackage.schemaRelationships + "/pivotTable");
partTbl.CreateRelationship(UriHelper.ResolvePartUri(tbl.Relationship.SourceUri, uriCd), tbl.CacheDefinition.Relationship.TargetMode, tbl.CacheDefinition.Relationship.RelationshipType);
partCd.CreateRelationship(UriHelper.ResolvePartUri(uriCd, uriRec), Packaging.TargetMode.Internal, ExcelPackage.schemaRelationships + "/pivotCacheRecords");
}
}
private void CopyHeaderFooterPictures(ExcelWorksheet Copy, ExcelWorksheet added)
{
if (Copy._headerFooter == null) return;
//Copy the texts
CopyText(Copy.HeaderFooter._oddHeader, added.HeaderFooter.OddHeader);
CopyText(Copy.HeaderFooter._oddFooter, added.HeaderFooter.OddFooter);
CopyText(Copy.HeaderFooter._evenHeader, added.HeaderFooter.EvenHeader);
CopyText(Copy.HeaderFooter._evenFooter, added.HeaderFooter.EvenFooter);
CopyText(Copy.HeaderFooter._firstHeader, added.HeaderFooter.FirstHeader);
CopyText(Copy.HeaderFooter._firstFooter, added.HeaderFooter.FirstFooter);
//Copy any images;
if (Copy.HeaderFooter.Pictures.Count > 0)
{
Uri source = Copy.HeaderFooter.Pictures.Uri;
Uri dest = XmlHelper.GetNewUri(_pck.Package, @"/xl/drawings/vmlDrawing{0}.vml");
//var part = _pck.Package.CreatePart(dest, "application/vnd.openxmlformats-officedocument.vmlDrawing", _pck.Compression);
foreach (ExcelVmlDrawingPicture pic in Copy.HeaderFooter.Pictures)
{
var item = added.HeaderFooter.Pictures.Add(pic.Id, pic.ImageUri, pic.Title, pic.Width, pic.Height);
foreach (XmlAttribute att in pic.TopNode.Attributes)
{
(item.TopNode as XmlElement).SetAttribute(att.Name, att.Value);
}
item.TopNode.InnerXml = pic.TopNode.InnerXml;
}
}
}
private void CopyText(ExcelHeaderFooterText from, ExcelHeaderFooterText to)
{
if (from == null) return;
to.LeftAlignedText=from.LeftAlignedText;
to.CenteredText = from.CenteredText;
to.RightAlignedText = from.RightAlignedText;
}
private void CloneCells(ExcelWorksheet Copy, ExcelWorksheet added)
{
bool sameWorkbook=(Copy.Workbook == _pck.Workbook);
bool doAdjust = _pck.DoAdjustDrawings;
_pck.DoAdjustDrawings = false;
added.MergedCells.List.AddRange(Copy.MergedCells.List);
//Formulas
//foreach (IRangeID f in Copy._formulaCells)
//{
// added._formulaCells.Add(f);
//}
//Shared Formulas
foreach (int key in Copy._sharedFormulas.Keys)
{
added._sharedFormulas.Add(key, Copy._sharedFormulas[key]);
}
Dictionary styleCashe = new Dictionary();
//Cells
int row,col;
var val = new CellsStoreEnumerator