public XLHeaderFooter(XLWorksheet worksheet) { Left = new XLHFItem(worksheet); Right = new XLHFItem(worksheet); Center = new XLHFItem(worksheet); SetAsInitial(); }
public XLHeaderFooter(XLHeaderFooter defaultHF, XLWorksheet worksheet) { defaultHF.innerTexts.ForEach(kp => innerTexts.Add(kp.Key, kp.Value)); Left = new XLHFItem(defaultHF.Left as XLHFItem, worksheet); Center = new XLHFItem(defaultHF.Center as XLHFItem, worksheet); Right = new XLHFItem(defaultHF.Right as XLHFItem, worksheet); SetAsInitial(); }
public XLPageSetup(XLPageSetup defaultPageOptions, XLWorksheet worksheet) { if (defaultPageOptions != null) { PrintAreas = new XLPrintAreas(defaultPageOptions.PrintAreas as XLPrintAreas, worksheet); CenterHorizontally = defaultPageOptions.CenterHorizontally; CenterVertically = defaultPageOptions.CenterVertically; FirstPageNumber = defaultPageOptions.FirstPageNumber; HorizontalDpi = defaultPageOptions.HorizontalDpi; PageOrientation = defaultPageOptions.PageOrientation; VerticalDpi = defaultPageOptions.VerticalDpi; PaperSize = defaultPageOptions.PaperSize; _pagesTall = defaultPageOptions.PagesTall; _pagesWide = defaultPageOptions.PagesWide; _scale = defaultPageOptions.Scale; if (defaultPageOptions.Margins != null) { Margins = new XLMargins { Top = defaultPageOptions.Margins.Top, Bottom = defaultPageOptions.Margins.Bottom, Left = defaultPageOptions.Margins.Left, Right = defaultPageOptions.Margins.Right, Header = defaultPageOptions.Margins.Header, Footer = defaultPageOptions.Margins.Footer }; } AlignHFWithMargins = defaultPageOptions.AlignHFWithMargins; ScaleHFWithDocument = defaultPageOptions.ScaleHFWithDocument; ShowGridlines = defaultPageOptions.ShowGridlines; ShowRowAndColumnHeadings = defaultPageOptions.ShowRowAndColumnHeadings; BlackAndWhite = defaultPageOptions.BlackAndWhite; DraftQuality = defaultPageOptions.DraftQuality; PageOrder = defaultPageOptions.PageOrder; ColumnBreaks = defaultPageOptions.ColumnBreaks.ToList(); RowBreaks = defaultPageOptions.RowBreaks.ToList(); Header = new XLHeaderFooter(defaultPageOptions.Header as XLHeaderFooter, worksheet); Footer = new XLHeaderFooter(defaultPageOptions.Footer as XLHeaderFooter, worksheet); PrintErrorValue = defaultPageOptions.PrintErrorValue; } else { PrintAreas = new XLPrintAreas(worksheet); Header = new XLHeaderFooter(worksheet); Footer = new XLHeaderFooter(worksheet); ColumnBreaks = new List<Int32>(); RowBreaks = new List<Int32>(); } }
public static XLAddress Create(XLWorksheet worksheet, string cellAddressString) { var fixedColumn = cellAddressString[0] == '$'; Int32 startPos; if (fixedColumn) { startPos = 1; } else { startPos = 0; } int rowPos = startPos; while (cellAddressString[rowPos] > '9') { rowPos++; } var fixedRow = cellAddressString[rowPos] == '$'; string columnLetter; int rowNumber; if (fixedRow) { if (fixedColumn) { columnLetter = cellAddressString.Substring(startPos, rowPos - 1); } else { columnLetter = cellAddressString.Substring(startPos, rowPos); } rowNumber = int.Parse(cellAddressString.Substring(rowPos + 1), XLHelper.NumberFormatForParse); } else { if (fixedColumn) { columnLetter = cellAddressString.Substring(startPos, rowPos - 1); } else { columnLetter = cellAddressString.Substring(startPos, rowPos); } rowNumber = Int32.Parse(cellAddressString.Substring(rowPos), XLHelper.NumberFormatForParse); } return new XLAddress(worksheet, rowNumber, columnLetter, fixedRow, fixedColumn); }
public XLRangeAddress(XLWorksheet worksheet, String rangeAddress) { string addressToUse = rangeAddress.Contains("!") ? rangeAddress.Substring(rangeAddress.IndexOf("!") + 1) : rangeAddress; string firstPart; string secondPart; if (addressToUse.Contains(':')) { var arrRange = addressToUse.Split(':'); firstPart = arrRange[0]; secondPart = arrRange[1]; } else { firstPart = addressToUse; secondPart = addressToUse; } if (XLHelper.IsValidA1Address(firstPart)) { FirstAddress = XLAddress.Create(worksheet, firstPart); LastAddress = XLAddress.Create(worksheet, secondPart); } else { firstPart = firstPart.Replace("$", String.Empty); secondPart = secondPart.Replace("$", String.Empty); if (char.IsDigit(firstPart[0])) { FirstAddress = XLAddress.Create(worksheet, "A" + firstPart); LastAddress = XLAddress.Create(worksheet, XLHelper.MaxColumnLetter + secondPart); } else { FirstAddress = XLAddress.Create(worksheet, firstPart + "1"); LastAddress = XLAddress.Create(worksheet, secondPart + XLHelper.MaxRowNumber.ToStringLookup()); } } Worksheet = worksheet; }
internal CloseXMLExcelSheet(XLWorksheet obj) { _obj = obj; }
private static void GenerateTables(XLWorksheet worksheet, WorksheetPart worksheetPart, SaveContext context) { worksheetPart.Worksheet.RemoveAllChildren<TablePart>(); if (!worksheet.Tables.Any()) return; foreach (var table in worksheet.Tables) { var tableRelId = context.RelIdGenerator.GetNext(RelType.Workbook); var xlTable = (XLTable)table; xlTable.RelId = tableRelId; var tableDefinitionPart = worksheetPart.AddNewPart<TableDefinitionPart>(tableRelId); GenerateTableDefinitionPartContent(tableDefinitionPart, xlTable, context); } }
private static void GenerateWorksheetCommentsPartContent(WorksheetCommentsPart worksheetCommentsPart, XLWorksheet xlWorksheet) { var comments = new Comments(); var commentList = new CommentList(); var authorsDict = new Dictionary<String, Int32>(); foreach (var c in xlWorksheet.Internals.CellsCollection.GetCells(c => c.HasComment)) { var comment = new Comment {Reference = c.Address.ToStringRelative()}; var authorName = c.Comment.Author; Int32 authorId; if (!authorsDict.TryGetValue(authorName, out authorId)) { authorId = authorsDict.Count; authorsDict.Add(authorName, authorId); } comment.AuthorId = (UInt32)authorId; var commentText = new CommentText(); foreach (var rt in c.Comment) { commentText.Append(GetRun(rt)); } comment.Append(commentText); commentList.Append(comment); } var authors = new Authors(); foreach (var author in authorsDict.Select(a => new Author {Text = a.Key})) { authors.Append(author); } comments.Append(authors); comments.Append(commentList); worksheetCommentsPart.Comments = comments; }
/// <summary> /// Initializes a new <see cref = "XLAddress" /> struct using R1C1 notation. /// </summary> /// <param name = "worksheet"></param> /// <param name = "rowNumber">The row number of the cell address.</param> /// <param name = "columnNumber">The column number of the cell address.</param> /// <param name = "fixedRow"></param> /// <param name = "fixedColumn"></param> public XLAddress(XLWorksheet worksheet, int rowNumber, int columnNumber, bool fixedRow, bool fixedColumn) { Worksheet = worksheet; _rowNumber = rowNumber; _columnNumber = columnNumber; _columnLetter = null; _fixedColumn = fixedColumn; _fixedRow = fixedRow; }
/// <summary> /// Initializes a new <see cref = "XLAddress" /> struct using a mixed notation. /// </summary> /// <param name = "worksheet"></param> /// <param name = "rowNumber">The row number of the cell address.</param> /// <param name = "columnLetter">The column letter of the cell address.</param> /// <param name = "fixedRow"></param> /// <param name = "fixedColumn"></param> public XLAddress(XLWorksheet worksheet, int rowNumber, string columnLetter, bool fixedRow, bool fixedColumn) : this(worksheet, rowNumber, XLHelper.GetColumnNumberFromLetter(columnLetter), fixedRow, fixedColumn) { _columnLetter = columnLetter; }
internal void SwapRanges(XLSheetRange sheetRange1, XLSheetRange sheetRange2, XLWorksheet worksheet) { Int32 rowCount = sheetRange1.LastPoint.Row - sheetRange1.FirstPoint.Row + 1; Int32 columnCount = sheetRange1.LastPoint.Column - sheetRange1.FirstPoint.Column + 1; for (int row = 0; row < rowCount; row++) { for (int column = 0; column < columnCount; column++) { var sp1 = new XLSheetPoint(sheetRange1.FirstPoint.Row + row, sheetRange1.FirstPoint.Column + column); var sp2 = new XLSheetPoint(sheetRange2.FirstPoint.Row + row, sheetRange2.FirstPoint.Column + column); var cell1 = GetCell(sp1); var cell2 = GetCell(sp2); if (cell1 == null) cell1 = worksheet.Cell(sp1.Row, sp1.Column); if (cell2 == null) cell2 = worksheet.Cell(sp2.Row, sp2.Column); //if (cell1 != null) //{ cell1.Address = new XLAddress(cell1.Worksheet, sp2.Row, sp2.Column, false, false); Remove(sp1); //if (cell2 != null) Add(sp1, cell2); //} //if (cell2 == null) continue; cell2.Address = new XLAddress(cell2.Worksheet, sp1.Row, sp1.Column, false, false); Remove(sp2); //if (cell1 != null) Add(sp2, cell1); } } }
public XLColumnParameters(XLWorksheet worksheet, Int32 defaultStyleId, Boolean isReference) { Worksheet = worksheet; DefaultStyleId = defaultStyleId; IsReference = isReference; }
public XLHFItem(XLWorksheet worksheet) { _worksheet = worksheet; }
public XLHFItem(XLHFItem defaultHFItem, XLWorksheet worksheet) :this(worksheet) { defaultHFItem.texts.ForEach(kp => texts.Add(kp.Key, kp.Value)); }
public XLHFText(XLRichString richText, XLWorksheet worksheet) { RichText = richText; _worksheet = worksheet; }
//private void GenerateDrawingsPartContent(DrawingsPart drawingsPart, XLWorksheet worksheet) //{ // if (drawingsPart.WorksheetDrawing == null) // drawingsPart.WorksheetDrawing = new Xdr.WorksheetDrawing(); // var worksheetDrawing = drawingsPart.WorksheetDrawing; // if (!worksheetDrawing.NamespaceDeclarations.Contains(new KeyValuePair<string, string>("xdr", "http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing"))) // worksheetDrawing.AddNamespaceDeclaration("xdr", "http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing"); // if (!worksheetDrawing.NamespaceDeclarations.Contains(new KeyValuePair<string, string>("a", "http://schemas.openxmlformats.org/drawingml/2006/main"))) // worksheetDrawing.AddNamespaceDeclaration("a", "http://schemas.openxmlformats.org/drawingml/2006/main"); // foreach (var chart in worksheet.Charts.OrderBy(c => c.ZOrder).Select(c => c)) // { // Xdr.TwoCellAnchor twoCellAnchor = new Xdr.TwoCellAnchor(); // worksheetDrawing.AppendChild(twoCellAnchor); // if (chart.Anchor == XLDrawingAnchor.MoveAndSizeWithCells) // twoCellAnchor.EditAs = Xdr.EditAsValues.TwoCell; // else if (chart.Anchor == XLDrawingAnchor.MoveWithCells) // twoCellAnchor.EditAs = Xdr.EditAsValues.OneCell; // else // twoCellAnchor.EditAs = Xdr.EditAsValues.Absolute; // if (twoCellAnchor.FromMarker == null) // twoCellAnchor.FromMarker = new Xdr.FromMarker(); // twoCellAnchor.FromMarker.RowId = new Xdr.RowId((chart.FirstRow - 1).ToString()); // twoCellAnchor.FromMarker.RowOffset = new Xdr.RowOffset(chart.FirstRowOffset.ToString()); // twoCellAnchor.FromMarker.ColumnId = new Xdr.ColumnId((chart.FirstColumn - 1).ToString()); // twoCellAnchor.FromMarker.ColumnOffset = new Xdr.ColumnOffset(chart.FirstColumnOffset.ToString()); // if (twoCellAnchor.ToMarker == null) // twoCellAnchor.ToMarker = new Xdr.ToMarker(); // twoCellAnchor.ToMarker.RowId = new Xdr.RowId((chart.LastRow - 1).ToString()); // twoCellAnchor.ToMarker.RowOffset = new Xdr.RowOffset(chart.LastRowOffset.ToString()); // twoCellAnchor.ToMarker.ColumnId = new Xdr.ColumnId((chart.LastColumn - 1).ToString()); // twoCellAnchor.ToMarker.ColumnOffset = new Xdr.ColumnOffset(chart.LastColumnOffset.ToString()); // Xdr.GraphicFrame graphicFrame = new Xdr.GraphicFrame(); // twoCellAnchor.AppendChild(graphicFrame); // if (graphicFrame.NonVisualGraphicFrameProperties == null) // graphicFrame.NonVisualGraphicFrameProperties = new Xdr.NonVisualGraphicFrameProperties(); // if (graphicFrame.NonVisualGraphicFrameProperties.NonVisualDrawingProperties == null) // graphicFrame.NonVisualGraphicFrameProperties.NonVisualDrawingProperties = new Xdr.NonVisualDrawingProperties() { Id = (UInt32)chart.Id, Name = chart.Name, Description = chart.Description, Hidden = chart.Hidden }; // if (graphicFrame.NonVisualGraphicFrameProperties.NonVisualGraphicFrameDrawingProperties == null) // graphicFrame.NonVisualGraphicFrameProperties.NonVisualGraphicFrameDrawingProperties = new Xdr.NonVisualGraphicFrameDrawingProperties(); // if (graphicFrame.Transform == null) // graphicFrame.Transform = new Xdr.Transform(); // if (chart.HorizontalFlip) // graphicFrame.Transform.HorizontalFlip = true; // else // graphicFrame.Transform.HorizontalFlip = null; // if (chart.VerticalFlip) // graphicFrame.Transform.VerticalFlip = true; // else // graphicFrame.Transform.VerticalFlip = null; // if (chart.Rotation != 0) // graphicFrame.Transform.Rotation = chart.Rotation; // else // graphicFrame.Transform.Rotation = null; // if (graphicFrame.Transform.Offset == null) // graphicFrame.Transform.Offset = new A.Offset(); // graphicFrame.Transform.Offset.X = chart.OffsetX; // graphicFrame.Transform.Offset.Y = chart.OffsetY; // if (graphicFrame.Transform.Extents == null) // graphicFrame.Transform.Extents = new A.Extents(); // graphicFrame.Transform.Extents.Cx = chart.ExtentLength; // graphicFrame.Transform.Extents.Cy = chart.ExtentWidth; // if (graphicFrame.Graphic == null) // graphicFrame.Graphic = new A.Graphic(); // if (graphicFrame.Graphic.GraphicData == null) // graphicFrame.Graphic.GraphicData = new A.GraphicData() { Uri = "http://schemas.openxmlformats.org/drawingml/2006/chart" }; // if (!graphicFrame.Graphic.GraphicData.Elements<C.ChartReference>().Any()) // { // C.ChartReference chartReference = new C.ChartReference() { Id = "rId" + chart.Id.ToStringLookup() }; // chartReference.AddNamespaceDeclaration("c", "http://schemas.openxmlformats.org/drawingml/2006/chart"); // chartReference.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships"); // graphicFrame.Graphic.GraphicData.AppendChild(chartReference); // } // if (!twoCellAnchor.Elements<Xdr.ClientData>().Any()) // twoCellAnchor.AppendChild(new Xdr.ClientData()); // } //} //private void GenerateChartPartContent(ChartPart chartPart, XLChart xlChart) //{ // if (chartPart.ChartSpace == null) // chartPart.ChartSpace = new C.ChartSpace(); // C.ChartSpace chartSpace = chartPart.ChartSpace; // if (!chartSpace.NamespaceDeclarations.Contains(new KeyValuePair<string, string>("c", "http://schemas.openxmlformats.org/drawingml/2006/chart"))) // chartSpace.AddNamespaceDeclaration("c", "http://schemas.openxmlformats.org/drawingml/2006/chart"); // if (!chartSpace.NamespaceDeclarations.Contains(new KeyValuePair<string, string>("a", "http://schemas.openxmlformats.org/drawingml/2006/main"))) // chartSpace.AddNamespaceDeclaration("a", "http://schemas.openxmlformats.org/drawingml/2006/main"); // if (!chartSpace.NamespaceDeclarations.Contains(new KeyValuePair<string, string>("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships"))) // chartSpace.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships"); // if (chartSpace.EditingLanguage == null) // chartSpace.EditingLanguage = new C.EditingLanguage() { Val = CultureInfo.CurrentCulture.Name }; // else // chartSpace.EditingLanguage.Val = CultureInfo.CurrentCulture.Name; // C.Chart chart = new C.Chart(); // chartSpace.AppendChild(chart); // if (chart.Title == null) // chart.Title = new C.Title(); // if (chart.Title.Layout == null) // chart.Title.Layout = new C.Layout(); // if (chart.View3D == null) // chart.View3D = new C.View3D(); // if (chart.View3D.RightAngleAxes == null) // chart.View3D.RightAngleAxes = new C.RightAngleAxes(); // chart.View3D.RightAngleAxes.Val = xlChart.RightAngleAxes; // if (chart.PlotArea == null) // chart.PlotArea = new C.PlotArea(); // if (chart.PlotArea.Layout == null) // chart.PlotArea.Layout = new C.Layout(); // OpenXmlElement chartElement = GetChartElement(xlChart); // chart.PlotArea.AppendChild(chartElement); // C.CategoryAxis categoryAxis1 = new C.CategoryAxis(); // C.AxisId axisId4 = new C.AxisId() { Val = (UInt32Value)71429120U }; // C.Scaling scaling1 = new C.Scaling(); // C.Orientation orientation1 = new C.Orientation() { Val = C.OrientationValues.MinMax }; // scaling1.AppendChild(orientation1); // C.AxisPosition axisPosition1 = new C.AxisPosition() { Val = C.AxisPositionValues.Bottom }; // C.TickLabelPosition tickLabelPosition1 = new C.TickLabelPosition() { Val = C.TickLabelPositionValues.NextTo }; // C.CrossingAxis crossingAxis1 = new C.CrossingAxis() { Val = (UInt32Value)71432064U }; // C.Crosses crosses1 = new C.Crosses() { Val = C.CrossesValues.AutoZero }; // C.AutoLabeled autoLabeled1 = new C.AutoLabeled() { Val = true }; // C.LabelAlignment labelAlignment1 = new C.LabelAlignment() { Val = C.LabelAlignmentValues.Center }; // C.LabelOffset labelOffset1 = new C.LabelOffset() { Val = (UInt16Value)100U }; // categoryAxis1.AppendChild(axisId4); // categoryAxis1.AppendChild(scaling1); // categoryAxis1.AppendChild(axisPosition1); // categoryAxis1.AppendChild(tickLabelPosition1); // categoryAxis1.AppendChild(crossingAxis1); // categoryAxis1.AppendChild(crosses1); // categoryAxis1.AppendChild(autoLabeled1); // categoryAxis1.AppendChild(labelAlignment1); // categoryAxis1.AppendChild(labelOffset1); // C.ValueAxis valueAxis1 = new C.ValueAxis(); // C.AxisId axisId5 = new C.AxisId() { Val = (UInt32Value)71432064U }; // C.Scaling scaling2 = new C.Scaling(); // C.Orientation orientation2 = new C.Orientation() { Val = C.OrientationValues.MinMax }; // scaling2.AppendChild(orientation2); // C.AxisPosition axisPosition2 = new C.AxisPosition() { Val = C.AxisPositionValues.Left }; // C.MajorGridlines majorGridlines1 = new C.MajorGridlines(); // C.NumberingFormat numberingFormat1 = new C.NumberingFormat() { FormatCode = "General", SourceLinked = true }; // C.TickLabelPosition tickLabelPosition2 = new C.TickLabelPosition() { Val = C.TickLabelPositionValues.NextTo }; // C.CrossingAxis crossingAxis2 = new C.CrossingAxis() { Val = (UInt32Value)71429120U }; // C.Crosses crosses2 = new C.Crosses() { Val = C.CrossesValues.AutoZero }; // C.CrossBetween crossBetween1 = new C.CrossBetween() { Val = C.CrossBetweenValues.Between }; // valueAxis1.AppendChild(axisId5); // valueAxis1.AppendChild(scaling2); // valueAxis1.AppendChild(axisPosition2); // valueAxis1.AppendChild(majorGridlines1); // valueAxis1.AppendChild(numberingFormat1); // valueAxis1.AppendChild(tickLabelPosition2); // valueAxis1.AppendChild(crossingAxis2); // valueAxis1.AppendChild(crosses2); // valueAxis1.AppendChild(crossBetween1); // plotArea.AppendChild(bar3DChart1); // plotArea.AppendChild(categoryAxis1); // plotArea.AppendChild(valueAxis1); // C.Legend legend1 = new C.Legend(); // C.LegendPosition legendPosition1 = new C.LegendPosition() { Val = C.LegendPositionValues.Right }; // C.Layout layout3 = new C.Layout(); // legend1.AppendChild(legendPosition1); // legend1.AppendChild(layout3); // C.PlotVisibleOnly plotVisibleOnly1 = new C.PlotVisibleOnly() { Val = true }; // chart.AppendChild(legend1); // chart.AppendChild(plotVisibleOnly1); // C.PrintSettings printSettings1 = new C.PrintSettings(); // C.HeaderFooter headerFooter1 = new C.HeaderFooter(); // C.PageMargins pageMargins4 = new C.PageMargins() { Left = 0.70000000000000018D, Right = 0.70000000000000018D, Top = 0.75000000000000022D, Bottom = 0.75000000000000022D, Header = 0.3000000000000001D, Footer = 0.3000000000000001D }; // C.PageSetup pageSetup1 = new C.PageSetup(); // printSettings1.AppendChild(headerFooter1); // printSettings1.AppendChild(pageMargins4); // printSettings1.AppendChild(pageSetup1); // chartSpace.AppendChild(printSettings1); //} //private OpenXmlElement GetChartElement(XLChart xlChart) //{ // if (xlChart.ChartTypeCategory == XLChartTypeCategory.Bar3D) // return GetBar3DChart(xlChart); // else // return null; //} //private OpenXmlElement GetBar3DChart(XLChart xlChart) //{ // C.Bar3DChart bar3DChart = new C.Bar3DChart(); // bar3DChart.BarDirection = new C.BarDirection() { Val = GetBarDirection(xlChart) }; // bar3DChart.BarGrouping = new C.BarGrouping() { Val = GetBarGrouping(xlChart) }; // C.BarChartSeries barChartSeries = new C.BarChartSeries(); // barChartSeries.Index = new C.Index() { Val = (UInt32Value)0U }; // barChartSeries.Order = new C.Order() { Val = (UInt32Value)0U }; // C.SeriesText seriesText1 = new C.SeriesText(); // C.StringReference stringReference1 = new C.StringReference(); // C.Formula formula1 = new C.Formula(); // formula1.Text = "Sheet1!$B$1"; // stringReference1.AppendChild(formula1); // seriesText1.AppendChild(stringReference1); // C.CategoryAxisData categoryAxisData1 = new C.CategoryAxisData(); // C.StringReference stringReference2 = new C.StringReference(); // C.Formula formula2 = new C.Formula(); // formula2.Text = "Sheet1!$A$2:$A$3"; // C.StringCache stringCache2 = new C.StringCache(); // C.PointCount pointCount2 = new C.PointCount() { Val = (UInt32Value)2U }; // C.StringPoint stringPoint2 = new C.StringPoint() { Index = (UInt32Value)0U }; // C.NumericValue numericValue2 = new C.NumericValue(); // numericValue2.Text = "A"; // stringPoint2.AppendChild(numericValue2); // C.StringPoint stringPoint3 = new C.StringPoint() { Index = (UInt32Value)1U }; // C.NumericValue numericValue3 = new C.NumericValue(); // numericValue3.Text = "B"; // stringPoint3.AppendChild(numericValue3); // stringCache2.AppendChild(pointCount2); // stringCache2.AppendChild(stringPoint2); // stringCache2.AppendChild(stringPoint3); // stringReference2.AppendChild(formula2); // stringReference2.AppendChild(stringCache2); // categoryAxisData1.AppendChild(stringReference2); // C.Values values1 = new C.Values(); // C.NumberReference numberReference1 = new C.NumberReference(); // C.Formula formula3 = new C.Formula(); // formula3.Text = "Sheet1!$B$2:$B$3"; // C.NumberingCache numberingCache1 = new C.NumberingCache(); // C.FormatCode formatCode1 = new C.FormatCode(); // formatCode1.Text = "General"; // C.PointCount pointCount3 = new C.PointCount() { Val = (UInt32Value)2U }; // C.NumericPoint numericPoint1 = new C.NumericPoint() { Index = (UInt32Value)0U }; // C.NumericValue numericValue4 = new C.NumericValue(); // numericValue4.Text = "5"; // numericPoint1.AppendChild(numericValue4); // C.NumericPoint numericPoint2 = new C.NumericPoint() { Index = (UInt32Value)1U }; // C.NumericValue numericValue5 = new C.NumericValue(); // numericValue5.Text = "10"; // numericPoint2.AppendChild(numericValue5); // numberingCache1.AppendChild(formatCode1); // numberingCache1.AppendChild(pointCount3); // numberingCache1.AppendChild(numericPoint1); // numberingCache1.AppendChild(numericPoint2); // numberReference1.AppendChild(formula3); // numberReference1.AppendChild(numberingCache1); // values1.AppendChild(numberReference1); // barChartSeries.AppendChild(index1); // barChartSeries.AppendChild(order1); // barChartSeries.AppendChild(seriesText1); // barChartSeries.AppendChild(categoryAxisData1); // barChartSeries.AppendChild(values1); // C.Shape shape1 = new C.Shape() { Val = C.ShapeValues.Box }; // C.AxisId axisId1 = new C.AxisId() { Val = (UInt32Value)71429120U }; // C.AxisId axisId2 = new C.AxisId() { Val = (UInt32Value)71432064U }; // C.AxisId axisId3 = new C.AxisId() { Val = (UInt32Value)0U }; // bar3DChart.AppendChild(barChartSeries); // bar3DChart.AppendChild(shape1); // bar3DChart.AppendChild(axisId1); // bar3DChart.AppendChild(axisId2); // bar3DChart.AppendChild(axisId3); // return bar3DChart; //} //private C.BarGroupingValues GetBarGrouping(XLChart xlChart) //{ // if (xlChart.BarGrouping == XLBarGrouping.Clustered) // return C.BarGroupingValues.Clustered; // else if (xlChart.BarGrouping == XLBarGrouping.Percent) // return C.BarGroupingValues.PercentStacked; // else if (xlChart.BarGrouping == XLBarGrouping.Stacked) // return C.BarGroupingValues.Stacked; // else // return C.BarGroupingValues.Standard; //} //private C.BarDirectionValues GetBarDirection(XLChart xlChart) //{ // if (xlChart.BarOrientation == XLBarOrientation.Vertical) // return C.BarDirectionValues.Column; // else // return C.BarDirectionValues.Bar; //} //-- private static void GeneratePivotTables(WorkbookPart workbookPart, WorksheetPart worksheetPart, XLWorksheet xlWorksheet, SaveContext context) { foreach (var pt in xlWorksheet.PivotTables) { var ptCdp = context.RelIdGenerator.GetNext(RelType.Workbook); var pivotTableCacheDefinitionPart = workbookPart.AddNewPart<PivotTableCacheDefinitionPart>(ptCdp); GeneratePivotTableCacheDefinitionPartContent(pivotTableCacheDefinitionPart, pt); var pivotCaches = new PivotCaches(); var pivotCache = new PivotCache {CacheId = 0U, Id = ptCdp}; pivotCaches.AppendChild(pivotCache); workbookPart.Workbook.AppendChild(pivotCaches); var pivotTablePart = worksheetPart.AddNewPart<PivotTablePart>(context.RelIdGenerator.GetNext(RelType.Workbook)); GeneratePivotTablePartContent(pivotTablePart, pt); pivotTablePart.AddPart(pivotTableCacheDefinitionPart, context.RelIdGenerator.GetNext(RelType.Workbook)); } }
private void DeleteComments(WorksheetPart worksheetPart, XLWorksheet worksheet, SaveContext context) { // We have the comments so we can delete the comments part worksheetPart.DeletePart(worksheetPart.WorksheetCommentsPart); var vmlDrawingPart = worksheetPart.VmlDrawingParts.FirstOrDefault(); // Only delete the VmlDrawingParts for comments. if (vmlDrawingPart != null) { var xdoc = XDocumentExtensions.Load(vmlDrawingPart.GetStream(FileMode.Open)); //xdoc.Root.Elements().Where(e => e.Name.LocalName == "shapelayout").Remove(); xdoc.Root.Elements().Where( e => e.Name.LocalName == "shapetype" && (string)e.Attribute("id") == @"_x0000_t202").Remove(); xdoc.Root.Elements().Where( e => e.Name.LocalName == "shape" && (string)e.Attribute("type") == @"#_x0000_t202").Remove(); var imageParts = vmlDrawingPart.ImageParts.ToList(); var legacyParts = vmlDrawingPart.LegacyDiagramTextParts.ToList(); var rId = worksheetPart.GetIdOfPart(vmlDrawingPart); worksheet.LegacyDrawingId = rId; worksheetPart.ChangeIdOfPart(vmlDrawingPart, "xxRRxx"); // Anything will do for the new relationship id // we just want it alive enough to create the copy var hasShapes = xdoc.Root.Elements().Any(e => e.Name.LocalName == "shape" || e.Name.LocalName == "group"); VmlDrawingPart vmlDrawingPartNew = null; var hasNewPart = (imageParts.Count > 0 || legacyParts.Count > 0 || hasShapes); if (hasNewPart) { vmlDrawingPartNew = worksheetPart.AddNewPart<VmlDrawingPart>(rId); using (var writer = new XmlTextWriter(vmlDrawingPartNew.GetStream(FileMode.Create), Encoding.UTF8)) { writer.WriteRaw(xdoc.ToString()); } imageParts.ForEach(p => vmlDrawingPartNew.AddPart(p, vmlDrawingPart.GetIdOfPart(p))); legacyParts.ForEach(p => vmlDrawingPartNew.AddPart(p, vmlDrawingPart.GetIdOfPart(p))); } worksheetPart.DeletePart(vmlDrawingPart); if (hasNewPart && rId != worksheetPart.GetIdOfPart(vmlDrawingPartNew)) worksheetPart.ChangeIdOfPart(vmlDrawingPartNew, rId); } }
public XLPrintAreas(XLPrintAreas defaultPrintAreas, XLWorksheet worksheet) { ranges = defaultPrintAreas.ranges.ToList(); this.worksheet = worksheet; }
// Generates content of vmlDrawingPart1. private static void GenerateVmlDrawingPartContent(VmlDrawingPart vmlDrawingPart, XLWorksheet xlWorksheet, SaveContext context) { var ms = new MemoryStream(); CopyStream(vmlDrawingPart.GetStream(FileMode.OpenOrCreate), ms); ms.Position = 0; var writer = new XmlTextWriter(vmlDrawingPart.GetStream(FileMode.Create), Encoding.UTF8); writer.WriteStartElement("xml"); const string shapeTypeId = "_x0000_t202"; // arbitrary, assigned by office new Vml.Shapetype( new Vml.Stroke {JoinStyle = Vml.StrokeJoinStyleValues.Miter}, new Vml.Path {AllowGradientShape = true, ConnectionPointType = ConnectValues.Rectangle} ) { Id = shapeTypeId, CoordinateSize = "21600,21600", OptionalNumber = 202, EdgePath = "m,l,21600r21600,l21600,xe", } .WriteTo(writer); var cellWithComments = xlWorksheet.Internals.CellsCollection.GetCells().Where(c => c.HasComment); foreach (var c in cellWithComments) { GenerateShape(c, shapeTypeId).WriteTo(writer); } if (ms.Length > 0) { ms.Position = 0; var xdoc = XDocumentExtensions.Load(ms); xdoc.Root.Elements().ForEach(e => writer.WriteRaw(e.ToString())); } writer.WriteEndElement(); writer.Flush(); writer.Close(); }
public XLPrintAreas(XLWorksheet worksheet) { this.worksheet = worksheet; }
private static void GenerateWorksheetPartContent(WorksheetPart worksheetPart, XLWorksheet xlWorksheet, SaveContext context) { #region Worksheet if (worksheetPart.Worksheet == null) worksheetPart.Worksheet = new Worksheet(); GenerateTables(xlWorksheet, worksheetPart, context); if ( !worksheetPart.Worksheet.NamespaceDeclarations.Contains(new KeyValuePair<String, String>("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships"))) { worksheetPart.Worksheet.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships"); } #endregion var cm = new XLWSContentManager(worksheetPart.Worksheet); #region SheetProperties if (worksheetPart.Worksheet.SheetProperties == null) worksheetPart.Worksheet.SheetProperties = new SheetProperties(); worksheetPart.Worksheet.SheetProperties.TabColor = xlWorksheet.TabColor.HasValue ? GetTabColor(xlWorksheet.TabColor) : null; cm.SetElement(XLWSContentManager.XLWSContents.SheetProperties, worksheetPart.Worksheet.SheetProperties); if (worksheetPart.Worksheet.SheetProperties.OutlineProperties == null) worksheetPart.Worksheet.SheetProperties.OutlineProperties = new OutlineProperties(); worksheetPart.Worksheet.SheetProperties.OutlineProperties.SummaryBelow = (xlWorksheet.Outline.SummaryVLocation == XLOutlineSummaryVLocation.Bottom); worksheetPart.Worksheet.SheetProperties.OutlineProperties.SummaryRight = (xlWorksheet.Outline.SummaryHLocation == XLOutlineSummaryHLocation.Right); if (worksheetPart.Worksheet.SheetProperties.PageSetupProperties == null && (xlWorksheet.PageSetup.PagesTall > 0 || xlWorksheet.PageSetup.PagesWide > 0)) worksheetPart.Worksheet.SheetProperties.PageSetupProperties = new PageSetupProperties {FitToPage = true}; #endregion var maxColumn = 0; var sheetDimensionReference = "A1"; if (xlWorksheet.Internals.CellsCollection.Count > 0) { maxColumn = xlWorksheet.Internals.CellsCollection.MaxColumnUsed; var maxRow = xlWorksheet.Internals.CellsCollection.MaxRowUsed; sheetDimensionReference = "A1:" + XLHelper.GetColumnLetterFromNumber(maxColumn) + maxRow.ToStringLookup(); } if (xlWorksheet.Internals.ColumnsCollection.Count > 0) { var maxColCollection = xlWorksheet.Internals.ColumnsCollection.Keys.Max(); if (maxColCollection > maxColumn) maxColumn = maxColCollection; } #region SheetViews if (worksheetPart.Worksheet.SheetDimension == null) worksheetPart.Worksheet.SheetDimension = new SheetDimension {Reference = sheetDimensionReference}; cm.SetElement(XLWSContentManager.XLWSContents.SheetDimension, worksheetPart.Worksheet.SheetDimension); if (worksheetPart.Worksheet.SheetViews == null) worksheetPart.Worksheet.SheetViews = new SheetViews(); cm.SetElement(XLWSContentManager.XLWSContents.SheetViews, worksheetPart.Worksheet.SheetViews); var sheetView = (SheetView)worksheetPart.Worksheet.SheetViews.FirstOrDefault(); if (sheetView == null) { sheetView = new SheetView {WorkbookViewId = 0U}; worksheetPart.Worksheet.SheetViews.AppendChild(sheetView); } if (xlWorksheet.TabSelected) sheetView.TabSelected = true; else sheetView.TabSelected = null; if (xlWorksheet.ShowFormulas) sheetView.ShowFormulas = true; else sheetView.ShowFormulas = null; if (xlWorksheet.ShowGridLines) sheetView.ShowGridLines = null; else sheetView.ShowGridLines = false; if (xlWorksheet.ShowOutlineSymbols) sheetView.ShowOutlineSymbols = null; else sheetView.ShowOutlineSymbols = false; if (xlWorksheet.ShowRowColHeaders) sheetView.ShowRowColHeaders = null; else sheetView.ShowRowColHeaders = false; if (xlWorksheet.ShowRuler) sheetView.ShowRuler = null; else sheetView.ShowRuler = false; if (xlWorksheet.ShowWhiteSpace) sheetView.ShowWhiteSpace = null; else sheetView.ShowWhiteSpace = false; if (xlWorksheet.ShowZeros) sheetView.ShowZeros = null; else sheetView.ShowZeros = false; if (xlWorksheet.RightToLeft) sheetView.RightToLeft = true; else sheetView.RightToLeft = null; if (xlWorksheet.SheetView.View == XLSheetViewOptions.Normal) sheetView.View = null; else sheetView.View = xlWorksheet.SheetView.View.ToOpenXml(); var pane = sheetView.Elements<Pane>().FirstOrDefault(); if (pane == null) { pane = new Pane(); sheetView.AppendChild(pane); } pane.State = PaneStateValues.FrozenSplit; Double hSplit = xlWorksheet.SheetView.SplitColumn; Double ySplit = xlWorksheet.SheetView.SplitRow; pane.HorizontalSplit = hSplit; pane.VerticalSplit = ySplit; pane.TopLeftCell = XLHelper.GetColumnLetterFromNumber(xlWorksheet.SheetView.SplitColumn + 1) + (xlWorksheet.SheetView.SplitRow + 1); if (hSplit == 0 && ySplit == 0) sheetView.RemoveAllChildren<Pane>(); if (xlWorksheet.SelectedRanges.Any() || xlWorksheet.ActiveCell != null) { sheetView.RemoveAllChildren<Selection>(); var firstSelection = xlWorksheet.SelectedRanges.FirstOrDefault(); var selection = new Selection(); if (xlWorksheet.ActiveCell != null) selection.ActiveCell = xlWorksheet.ActiveCell.Address.ToStringRelative(false); else if (firstSelection != null) selection.ActiveCell = firstSelection.RangeAddress.FirstAddress.ToStringRelative(false); var seqRef = new List<String> {selection.ActiveCell.Value}; seqRef.AddRange(xlWorksheet.SelectedRanges .Select(range => range.RangeAddress.ToStringRelative(false))); selection.SequenceOfReferences = new ListValue<StringValue> {InnerText = String.Join(" ", seqRef.Distinct().ToArray())}; sheetView.Append(selection); } #endregion var maxOutlineColumn = 0; if (xlWorksheet.ColumnCount() > 0) maxOutlineColumn = xlWorksheet.GetMaxColumnOutline(); var maxOutlineRow = 0; if (xlWorksheet.RowCount() > 0) maxOutlineRow = xlWorksheet.GetMaxRowOutline(); #region SheetFormatProperties if (worksheetPart.Worksheet.SheetFormatProperties == null) worksheetPart.Worksheet.SheetFormatProperties = new SheetFormatProperties(); cm.SetElement(XLWSContentManager.XLWSContents.SheetFormatProperties, worksheetPart.Worksheet.SheetFormatProperties); worksheetPart.Worksheet.SheetFormatProperties.DefaultRowHeight = xlWorksheet.RowHeight; if (xlWorksheet.RowHeightChanged) worksheetPart.Worksheet.SheetFormatProperties.CustomHeight = true; else worksheetPart.Worksheet.SheetFormatProperties.CustomHeight = null; var worksheetColumnWidth = GetColumnWidth(xlWorksheet.ColumnWidth); if (xlWorksheet.ColumnWidthChanged) worksheetPart.Worksheet.SheetFormatProperties.DefaultColumnWidth = worksheetColumnWidth; else worksheetPart.Worksheet.SheetFormatProperties.DefaultColumnWidth = null; if (maxOutlineColumn > 0) worksheetPart.Worksheet.SheetFormatProperties.OutlineLevelColumn = (byte)maxOutlineColumn; else worksheetPart.Worksheet.SheetFormatProperties.OutlineLevelColumn = null; if (maxOutlineRow > 0) worksheetPart.Worksheet.SheetFormatProperties.OutlineLevelRow = (byte)maxOutlineRow; else worksheetPart.Worksheet.SheetFormatProperties.OutlineLevelRow = null; #endregion #region Columns if (xlWorksheet.Internals.CellsCollection.Count == 0 && xlWorksheet.Internals.ColumnsCollection.Count == 0 && xlWorksheet.Style.Equals(DefaultStyle)) worksheetPart.Worksheet.RemoveAllChildren<Columns>(); else { if (!worksheetPart.Worksheet.Elements<Columns>().Any()) { var previousElement = cm.GetPreviousElementFor(XLWSContentManager.XLWSContents.Columns); worksheetPart.Worksheet.InsertAfter(new Columns(), previousElement); } var columns = worksheetPart.Worksheet.Elements<Columns>().First(); cm.SetElement(XLWSContentManager.XLWSContents.Columns, columns); var sheetColumnsByMin = columns.Elements<Column>().ToDictionary(c => c.Min.Value, c => c); //Dictionary<UInt32, Column> sheetColumnsByMax = columns.Elements<Column>().ToDictionary(c => c.Max.Value, c => c); Int32 minInColumnsCollection; Int32 maxInColumnsCollection; if (xlWorksheet.Internals.ColumnsCollection.Count > 0) { minInColumnsCollection = xlWorksheet.Internals.ColumnsCollection.Keys.Min(); maxInColumnsCollection = xlWorksheet.Internals.ColumnsCollection.Keys.Max(); } else { minInColumnsCollection = 1; maxInColumnsCollection = 0; } var worksheetStyleId = context.SharedStyles[xlWorksheet.GetStyleId()].StyleId; if (minInColumnsCollection > 1) { UInt32Value min = 1; UInt32Value max = (UInt32)(minInColumnsCollection - 1); for (var co = min; co <= max; co++) { var column = new Column { Min = co, Max = co, Style = worksheetStyleId, Width = worksheetColumnWidth, CustomWidth = true }; UpdateColumn(column, columns, sheetColumnsByMin); //, sheetColumnsByMax); } } for (var co = minInColumnsCollection; co <= maxInColumnsCollection; co++) { UInt32 styleId; Double columnWidth; var isHidden = false; var collapsed = false; var outlineLevel = 0; if (xlWorksheet.Internals.ColumnsCollection.ContainsKey(co)) { styleId = context.SharedStyles[xlWorksheet.Internals.ColumnsCollection[co].GetStyleId()].StyleId; columnWidth = GetColumnWidth(xlWorksheet.Internals.ColumnsCollection[co].Width); isHidden = xlWorksheet.Internals.ColumnsCollection[co].IsHidden; collapsed = xlWorksheet.Internals.ColumnsCollection[co].Collapsed; outlineLevel = xlWorksheet.Internals.ColumnsCollection[co].OutlineLevel; } else { styleId = context.SharedStyles[xlWorksheet.GetStyleId()].StyleId; columnWidth = worksheetColumnWidth; } var column = new Column { Min = (UInt32)co, Max = (UInt32)co, Style = styleId, Width = columnWidth, CustomWidth = true }; if (isHidden) column.Hidden = true; if (collapsed) column.Collapsed = true; if (outlineLevel > 0) column.OutlineLevel = (byte)outlineLevel; UpdateColumn(column, columns, sheetColumnsByMin); //, sheetColumnsByMax); } var collection = maxInColumnsCollection; foreach ( var col in columns.Elements<Column>().Where(c => c.Min > (UInt32)(collection)).OrderBy( c => c.Min.Value)) { col.Style = worksheetStyleId; col.Width = worksheetColumnWidth; col.CustomWidth = true; if ((Int32)col.Max.Value > maxInColumnsCollection) maxInColumnsCollection = (Int32)col.Max.Value; } if (maxInColumnsCollection < XLHelper.MaxColumnNumber && !xlWorksheet.Style.Equals(DefaultStyle)) { var column = new Column { Min = (UInt32)(maxInColumnsCollection + 1), Max = (UInt32)(XLHelper.MaxColumnNumber), Style = worksheetStyleId, Width = worksheetColumnWidth, CustomWidth = true }; columns.AppendChild(column); } CollapseColumns(columns, sheetColumnsByMin); if (!columns.Any()) { worksheetPart.Worksheet.RemoveAllChildren<Columns>(); cm.SetElement(XLWSContentManager.XLWSContents.Columns, null); } } #endregion #region SheetData if (!worksheetPart.Worksheet.Elements<SheetData>().Any()) { var previousElement = cm.GetPreviousElementFor(XLWSContentManager.XLWSContents.SheetData); worksheetPart.Worksheet.InsertAfter(new SheetData(), previousElement); } var sheetData = worksheetPart.Worksheet.Elements<SheetData>().First(); cm.SetElement(XLWSContentManager.XLWSContents.SheetData, sheetData); var cellsByRow = new Dictionary<Int32, List<IXLCell>>(); foreach (var c in xlWorksheet.Internals.CellsCollection.GetCells()) { var rowNum = c.Address.RowNumber; if (!cellsByRow.ContainsKey(rowNum)) cellsByRow.Add(rowNum, new List<IXLCell>()); cellsByRow[rowNum].Add(c); } var lastRow = 0; var sheetDataRows = sheetData.Elements<Row>().ToDictionary(r => r.RowIndex == null ? ++lastRow : (Int32)r.RowIndex.Value, r => r); foreach ( var r in xlWorksheet.Internals.RowsCollection.Deleted.Where(r => sheetDataRows.ContainsKey(r.Key))) { sheetData.RemoveChild(sheetDataRows[r.Key]); sheetDataRows.Remove(r.Key); xlWorksheet.Internals.CellsCollection.Deleted.RemoveWhere(d => d.Row == r.Key); } var distinctRows = cellsByRow.Keys.Union(xlWorksheet.Internals.RowsCollection.Keys); var noRows = (sheetData.Elements<Row>().FirstOrDefault() == null); foreach (var distinctRow in distinctRows.OrderBy(r => r)) { Row row; // = sheetData.Elements<Row>().FirstOrDefault(r => r.RowIndex.Value == (UInt32)distinctRow); if (sheetDataRows.ContainsKey(distinctRow)) row = sheetDataRows[distinctRow]; else { row = new Row {RowIndex = (UInt32)distinctRow}; if (noRows) { sheetData.AppendChild(row); noRows = false; } else { if (sheetDataRows.Any(r => r.Key > row.RowIndex.Value)) { var minRow = sheetDataRows.Where(r => r.Key > (Int32)row.RowIndex.Value).Min(r => r.Key); var rowBeforeInsert = sheetDataRows[minRow]; sheetData.InsertBefore(row, rowBeforeInsert); } else sheetData.AppendChild(row); } } if (maxColumn > 0) row.Spans = new ListValue<StringValue> {InnerText = "1:" + maxColumn.ToStringLookup()}; row.Height = null; row.CustomHeight = null; row.Hidden = null; row.StyleIndex = null; row.CustomFormat = null; row.Collapsed = null; if (xlWorksheet.Internals.RowsCollection.ContainsKey(distinctRow)) { var thisRow = xlWorksheet.Internals.RowsCollection[distinctRow]; if (thisRow.HeightChanged) { row.Height = thisRow.Height; row.CustomHeight = true; row.CustomFormat = true; } if (thisRow.GetStyleId() != xlWorksheet.GetStyleId()) { row.StyleIndex = context.SharedStyles[thisRow.GetStyleId()].StyleId; row.CustomFormat = true; } if (thisRow.IsHidden) row.Hidden = true; if (thisRow.Collapsed) row.Collapsed = true; if (thisRow.OutlineLevel > 0) row.OutlineLevel = (byte)thisRow.OutlineLevel; } var lastCell = 0; var cellsByReference = row.Elements<Cell>().ToDictionary(c => c.CellReference == null ? XLHelper.GetColumnLetterFromNumber( ++lastCell) + distinctRow : c.CellReference.Value, c => c); foreach (var c in xlWorksheet.Internals.CellsCollection.Deleted.ToList()) { var key = XLHelper.GetColumnLetterFromNumber(c.Column) + c.Row.ToStringLookup(); if (!cellsByReference.ContainsKey(key)) continue; row.RemoveChild(cellsByReference[key]); xlWorksheet.Internals.CellsCollection.Deleted.Remove(c); } if (!cellsByRow.ContainsKey(distinctRow)) continue; var isNewRow = !row.Elements<Cell>().Any(); var mRows = row.Elements<Cell>().ToDictionary(c => XLHelper.GetColumnNumberFromAddress(c.CellReference.Value), c => c); foreach (var opCell in cellsByRow[distinctRow] .OrderBy(c => c.Address.ColumnNumber) .Select(c => (XLCell)c)) { var styleId = context.SharedStyles[opCell.GetStyleId()].StyleId; var dataType = opCell.DataType; var cellReference = (opCell.Address).GetTrimmedAddress(); Cell cell; if (cellsByReference.ContainsKey(cellReference)) cell = cellsByReference[cellReference]; else { cell = new Cell {CellReference = new StringValue(cellReference)}; if (isNewRow) row.AppendChild(cell); else { var newColumn = XLHelper.GetColumnNumberFromAddress(cellReference); Cell cellBeforeInsert = null; int[] lastCo = {Int32.MaxValue}; foreach (var c in mRows.Where(kp => kp.Key > newColumn).Where(c => lastCo[0] > c.Key)) { cellBeforeInsert = c.Value; lastCo[0] = c.Key; } if (cellBeforeInsert == null) row.AppendChild(cell); else row.InsertBefore(cell, cellBeforeInsert); } } cell.StyleIndex = styleId; var formula = opCell.FormulaA1; if (opCell.HasFormula) { if (formula.StartsWith("{")) { formula = formula.Substring(1, formula.Length - 2); var f = new CellFormula {FormulaType = CellFormulaValues.Array}; if (opCell.FormulaReference.FirstAddress.Equals(opCell.Address)) { f.Text = formula; f.Reference = opCell.FormulaReference.ToStringRelative(); } cell.CellFormula = f; } else cell.CellFormula = new CellFormula(formula); cell.CellValue = null; } else { cell.CellFormula = null; cell.DataType = opCell.DataType == XLCellValues.DateTime ? null : GetCellValue(opCell); var cellValue = new CellValue(); if (dataType == XLCellValues.Text) { if (opCell.InnerText.Length == 0) cell.CellValue = null; else { if (opCell.ShareString) { cellValue.Text = opCell.SharedStringId.ToString(); cell.CellValue = cellValue; } else { var text = opCell.GetString(); var t = new Text(text); if (text.PreserveSpaces()) t.Space = SpaceProcessingModeValues.Preserve; cell.InlineString = new InlineString {Text = t}; } } } else if (dataType == XLCellValues.TimeSpan) { var timeSpan = opCell.GetTimeSpan(); cellValue.Text = XLCell.BaseDate.Add(timeSpan).ToOADate().ToString(CultureInfo.InvariantCulture); cell.CellValue = cellValue; } else if (dataType == XLCellValues.DateTime || dataType == XLCellValues.Number) { if (!XLHelper.IsNullOrWhiteSpace(opCell.InnerText)) cellValue.Text = Double.Parse(opCell.InnerText).ToString(CultureInfo.InvariantCulture); cell.CellValue = cellValue; } else { cellValue.Text = opCell.InnerText; cell.CellValue = cellValue; } } } xlWorksheet.Internals.CellsCollection.Deleted.RemoveWhere(d => d.Row == distinctRow); } foreach ( var r in xlWorksheet.Internals.CellsCollection.Deleted.Select(c => c.Row).Distinct().Where( sheetDataRows.ContainsKey)) { sheetData.RemoveChild(sheetDataRows[r]); sheetDataRows.Remove(r); } #endregion #region SheetProtection if (xlWorksheet.Protection.Protected) { if (!worksheetPart.Worksheet.Elements<SheetProtection>().Any()) { var previousElement = cm.GetPreviousElementFor(XLWSContentManager.XLWSContents.SheetProtection); worksheetPart.Worksheet.InsertAfter(new SheetProtection(), previousElement); } var sheetProtection = worksheetPart.Worksheet.Elements<SheetProtection>().First(); cm.SetElement(XLWSContentManager.XLWSContents.SheetProtection, sheetProtection); var protection = xlWorksheet.Protection; sheetProtection.Sheet = protection.Protected; if (!XLHelper.IsNullOrWhiteSpace(protection.PasswordHash)) sheetProtection.Password = protection.PasswordHash; sheetProtection.FormatCells = GetBooleanValue(!protection.FormatCells, true); sheetProtection.FormatColumns = GetBooleanValue(!protection.FormatColumns, true); sheetProtection.FormatRows = GetBooleanValue(!protection.FormatRows, true); sheetProtection.InsertColumns = GetBooleanValue(!protection.InsertColumns, true); sheetProtection.InsertHyperlinks = GetBooleanValue(!protection.InsertHyperlinks, true); sheetProtection.InsertRows = GetBooleanValue(!protection.InsertRows, true); sheetProtection.DeleteColumns = GetBooleanValue(!protection.DeleteColumns, true); sheetProtection.DeleteRows = GetBooleanValue(!protection.DeleteRows, true); sheetProtection.AutoFilter = GetBooleanValue(!protection.AutoFilter, true); sheetProtection.PivotTables = GetBooleanValue(!protection.PivotTables, true); sheetProtection.Sort = GetBooleanValue(!protection.Sort, true); sheetProtection.SelectLockedCells = GetBooleanValue(!protection.SelectLockedCells, false); sheetProtection.SelectUnlockedCells = GetBooleanValue(!protection.SelectUnlockedCells, false); } else { worksheetPart.Worksheet.RemoveAllChildren<SheetProtection>(); cm.SetElement(XLWSContentManager.XLWSContents.SheetProtection, null); } #endregion #region AutoFilter worksheetPart.Worksheet.RemoveAllChildren<AutoFilter>(); if (xlWorksheet.AutoFilter.Enabled) { var previousElement = cm.GetPreviousElementFor(XLWSContentManager.XLWSContents.AutoFilter); worksheetPart.Worksheet.InsertAfter(new AutoFilter(), previousElement); var autoFilter = worksheetPart.Worksheet.Elements<AutoFilter>().First(); cm.SetElement(XLWSContentManager.XLWSContents.AutoFilter, autoFilter); PopulateAutoFilter(xlWorksheet.AutoFilter, autoFilter); } else { cm.SetElement(XLWSContentManager.XLWSContents.AutoFilter, null); } #endregion #region MergeCells if ((xlWorksheet).Internals.MergedRanges.Any()) { if (!worksheetPart.Worksheet.Elements<MergeCells>().Any()) { var previousElement = cm.GetPreviousElementFor(XLWSContentManager.XLWSContents.MergeCells); worksheetPart.Worksheet.InsertAfter(new MergeCells(), previousElement); } var mergeCells = worksheetPart.Worksheet.Elements<MergeCells>().First(); cm.SetElement(XLWSContentManager.XLWSContents.MergeCells, mergeCells); mergeCells.RemoveAllChildren<MergeCell>(); foreach (var mergeCell in (xlWorksheet).Internals.MergedRanges.Select( m => m.RangeAddress.FirstAddress.ToString() + ":" + m.RangeAddress.LastAddress.ToString()).Select( merged => new MergeCell {Reference = merged})) mergeCells.AppendChild(mergeCell); mergeCells.Count = (UInt32)mergeCells.Count(); } else { worksheetPart.Worksheet.RemoveAllChildren<MergeCells>(); cm.SetElement(XLWSContentManager.XLWSContents.MergeCells, null); } #endregion #region Conditional Formatting if (!xlWorksheet.ConditionalFormats.Any()) { worksheetPart.Worksheet.RemoveAllChildren<ConditionalFormatting>(); cm.SetElement(XLWSContentManager.XLWSContents.ConditionalFormatting, null); } else { worksheetPart.Worksheet.RemoveAllChildren<ConditionalFormatting>(); var previousElement = cm.GetPreviousElementFor(XLWSContentManager.XLWSContents.ConditionalFormatting); //if (!worksheetPart.Worksheet.Elements<ConditionalFormatting>().Any()) //{ // var previousElement = cm.GetPreviousElementFor(XLWSContentManager.XLWSContents.ConditionalFormatting); // worksheetPart.Worksheet.InsertAfter(new ConditionalFormatting(), previousElement); //} //var conditionalFormats = worksheetPart.Worksheet.Elements<ConditionalFormatting>().First(); //cm.SetElement(XLWSContentManager.XLWSContents.ConditionalFormatting, conditionalFormats); ////conditionalFormats.RemoveAllChildren<ConditionalFormat>(); var priority = 0; foreach (var cf in xlWorksheet.ConditionalFormats) { priority++; var conditionalFormatting = new ConditionalFormatting { SequenceOfReferences = new ListValue<StringValue> {InnerText = cf.Range.RangeAddress.ToStringRelative(false)} }; conditionalFormatting.Append(XLCFConverters.Convert(cf, priority, context)); worksheetPart.Worksheet.InsertAfter(conditionalFormatting, previousElement); previousElement = conditionalFormatting; cm.SetElement(XLWSContentManager.XLWSContents.ConditionalFormatting, conditionalFormatting); } } #endregion #region DataValidations if (!xlWorksheet.DataValidations.Any(d => d.IsDirty())) { worksheetPart.Worksheet.RemoveAllChildren<DataValidations>(); cm.SetElement(XLWSContentManager.XLWSContents.DataValidations, null); } else { if (!worksheetPart.Worksheet.Elements<DataValidations>().Any()) { var previousElement = cm.GetPreviousElementFor(XLWSContentManager.XLWSContents.DataValidations); worksheetPart.Worksheet.InsertAfter(new DataValidations(), previousElement); } var dataValidations = worksheetPart.Worksheet.Elements<DataValidations>().First(); cm.SetElement(XLWSContentManager.XLWSContents.DataValidations, dataValidations); dataValidations.RemoveAllChildren<DataValidation>(); foreach (var dv in xlWorksheet.DataValidations) { var sequence = dv.Ranges.Aggregate(String.Empty, (current, r) => current + (r.RangeAddress + " ")); if (sequence.Length > 0) sequence = sequence.Substring(0, sequence.Length - 1); var dataValidation = new DataValidation { AllowBlank = dv.IgnoreBlanks, Formula1 = new Formula1(dv.MinValue), Formula2 = new Formula2(dv.MaxValue), Type = dv.AllowedValues.ToOpenXml(), ShowErrorMessage = dv.ShowErrorMessage, Prompt = dv.InputMessage, PromptTitle = dv.InputTitle, ErrorTitle = dv.ErrorTitle, Error = dv.ErrorMessage, ShowDropDown = !dv.InCellDropdown, ShowInputMessage = dv.ShowInputMessage, ErrorStyle = dv.ErrorStyle.ToOpenXml(), Operator = dv.Operator.ToOpenXml(), SequenceOfReferences = new ListValue<StringValue> {InnerText = sequence} }; dataValidations.AppendChild(dataValidation); } dataValidations.Count = (UInt32)xlWorksheet.DataValidations.Count(); } #endregion #region Hyperlinks var relToRemove = worksheetPart.HyperlinkRelationships.ToList(); relToRemove.ForEach(worksheetPart.DeleteReferenceRelationship); if (!xlWorksheet.Hyperlinks.Any()) { worksheetPart.Worksheet.RemoveAllChildren<Hyperlinks>(); cm.SetElement(XLWSContentManager.XLWSContents.Hyperlinks, null); } else { if (!worksheetPart.Worksheet.Elements<Hyperlinks>().Any()) { var previousElement = cm.GetPreviousElementFor(XLWSContentManager.XLWSContents.Hyperlinks); worksheetPart.Worksheet.InsertAfter(new Hyperlinks(), previousElement); } var hyperlinks = worksheetPart.Worksheet.Elements<Hyperlinks>().First(); cm.SetElement(XLWSContentManager.XLWSContents.Hyperlinks, hyperlinks); hyperlinks.RemoveAllChildren<Hyperlink>(); foreach (var hl in xlWorksheet.Hyperlinks) { Hyperlink hyperlink; if (hl.IsExternal) { var rId = context.RelIdGenerator.GetNext(RelType.Workbook); hyperlink = new Hyperlink {Reference = hl.Cell.Address.ToString(), Id = rId}; worksheetPart.AddHyperlinkRelationship(hl.ExternalAddress, true, rId); } else { hyperlink = new Hyperlink { Reference = hl.Cell.Address.ToString(), Location = hl.InternalAddress, Display = hl.Cell.GetFormattedString() }; } if (!XLHelper.IsNullOrWhiteSpace(hl.Tooltip)) hyperlink.Tooltip = hl.Tooltip; hyperlinks.AppendChild(hyperlink); } } #endregion #region PrintOptions if (!worksheetPart.Worksheet.Elements<PrintOptions>().Any()) { var previousElement = cm.GetPreviousElementFor(XLWSContentManager.XLWSContents.PrintOptions); worksheetPart.Worksheet.InsertAfter(new PrintOptions(), previousElement); } var printOptions = worksheetPart.Worksheet.Elements<PrintOptions>().First(); cm.SetElement(XLWSContentManager.XLWSContents.PrintOptions, printOptions); printOptions.HorizontalCentered = xlWorksheet.PageSetup.CenterHorizontally; printOptions.VerticalCentered = xlWorksheet.PageSetup.CenterVertically; printOptions.Headings = xlWorksheet.PageSetup.ShowRowAndColumnHeadings; printOptions.GridLines = xlWorksheet.PageSetup.ShowGridlines; #endregion #region PageMargins if (!worksheetPart.Worksheet.Elements<PageMargins>().Any()) { var previousElement = cm.GetPreviousElementFor(XLWSContentManager.XLWSContents.PageMargins); worksheetPart.Worksheet.InsertAfter(new PageMargins(), previousElement); } var pageMargins = worksheetPart.Worksheet.Elements<PageMargins>().First(); cm.SetElement(XLWSContentManager.XLWSContents.PageMargins, pageMargins); pageMargins.Left = xlWorksheet.PageSetup.Margins.Left; pageMargins.Right = xlWorksheet.PageSetup.Margins.Right; pageMargins.Top = xlWorksheet.PageSetup.Margins.Top; pageMargins.Bottom = xlWorksheet.PageSetup.Margins.Bottom; pageMargins.Header = xlWorksheet.PageSetup.Margins.Header; pageMargins.Footer = xlWorksheet.PageSetup.Margins.Footer; #endregion #region PageSetup if (!worksheetPart.Worksheet.Elements<PageSetup>().Any()) { var previousElement = cm.GetPreviousElementFor(XLWSContentManager.XLWSContents.PageSetup); worksheetPart.Worksheet.InsertAfter(new PageSetup(), previousElement); } var pageSetup = worksheetPart.Worksheet.Elements<PageSetup>().First(); cm.SetElement(XLWSContentManager.XLWSContents.PageSetup, pageSetup); pageSetup.Orientation = xlWorksheet.PageSetup.PageOrientation.ToOpenXml(); pageSetup.PaperSize = (UInt32)xlWorksheet.PageSetup.PaperSize; pageSetup.BlackAndWhite = xlWorksheet.PageSetup.BlackAndWhite; pageSetup.Draft = xlWorksheet.PageSetup.DraftQuality; pageSetup.PageOrder = xlWorksheet.PageSetup.PageOrder.ToOpenXml(); pageSetup.CellComments = xlWorksheet.PageSetup.ShowComments.ToOpenXml(); pageSetup.Errors = xlWorksheet.PageSetup.PrintErrorValue.ToOpenXml(); if (xlWorksheet.PageSetup.FirstPageNumber > 0) { pageSetup.FirstPageNumber = (UInt32)xlWorksheet.PageSetup.FirstPageNumber; pageSetup.UseFirstPageNumber = true; } else { pageSetup.FirstPageNumber = null; pageSetup.UseFirstPageNumber = null; } if (xlWorksheet.PageSetup.HorizontalDpi > 0) pageSetup.HorizontalDpi = (UInt32)xlWorksheet.PageSetup.HorizontalDpi; else pageSetup.HorizontalDpi = null; if (xlWorksheet.PageSetup.VerticalDpi > 0) pageSetup.VerticalDpi = (UInt32)xlWorksheet.PageSetup.VerticalDpi; else pageSetup.VerticalDpi = null; if (xlWorksheet.PageSetup.Scale > 0) { pageSetup.Scale = (UInt32)xlWorksheet.PageSetup.Scale; pageSetup.FitToWidth = null; pageSetup.FitToHeight = null; } else { pageSetup.Scale = null; if (xlWorksheet.PageSetup.PagesWide > 0) pageSetup.FitToWidth = (UInt32)xlWorksheet.PageSetup.PagesWide; else pageSetup.FitToWidth = 0; if (xlWorksheet.PageSetup.PagesTall > 0) pageSetup.FitToHeight = (UInt32)xlWorksheet.PageSetup.PagesTall; else pageSetup.FitToHeight = 0; } #endregion #region HeaderFooter var headerFooter = worksheetPart.Worksheet.Elements<HeaderFooter>().FirstOrDefault(); if (headerFooter == null) headerFooter = new HeaderFooter(); else worksheetPart.Worksheet.RemoveAllChildren<HeaderFooter>(); { var previousElement = cm.GetPreviousElementFor(XLWSContentManager.XLWSContents.HeaderFooter); worksheetPart.Worksheet.InsertAfter(headerFooter, previousElement); cm.SetElement(XLWSContentManager.XLWSContents.HeaderFooter, headerFooter); } if (((XLHeaderFooter)xlWorksheet.PageSetup.Header).Changed || ((XLHeaderFooter)xlWorksheet.PageSetup.Footer).Changed) { //var headerFooter = worksheetPart.Worksheet.Elements<HeaderFooter>().First(); headerFooter.RemoveAllChildren(); headerFooter.ScaleWithDoc = xlWorksheet.PageSetup.ScaleHFWithDocument; headerFooter.AlignWithMargins = xlWorksheet.PageSetup.AlignHFWithMargins; headerFooter.DifferentFirst = xlWorksheet.PageSetup.DifferentFirstPageOnHF; headerFooter.DifferentOddEven = xlWorksheet.PageSetup.DifferentOddEvenPagesOnHF; var oddHeader = new OddHeader(xlWorksheet.PageSetup.Header.GetText(XLHFOccurrence.OddPages)); headerFooter.AppendChild(oddHeader); var oddFooter = new OddFooter(xlWorksheet.PageSetup.Footer.GetText(XLHFOccurrence.OddPages)); headerFooter.AppendChild(oddFooter); var evenHeader = new EvenHeader(xlWorksheet.PageSetup.Header.GetText(XLHFOccurrence.EvenPages)); headerFooter.AppendChild(evenHeader); var evenFooter = new EvenFooter(xlWorksheet.PageSetup.Footer.GetText(XLHFOccurrence.EvenPages)); headerFooter.AppendChild(evenFooter); var firstHeader = new FirstHeader(xlWorksheet.PageSetup.Header.GetText(XLHFOccurrence.FirstPage)); headerFooter.AppendChild(firstHeader); var firstFooter = new FirstFooter(xlWorksheet.PageSetup.Footer.GetText(XLHFOccurrence.FirstPage)); headerFooter.AppendChild(firstFooter); } #endregion #region RowBreaks if (!worksheetPart.Worksheet.Elements<RowBreaks>().Any()) { var previousElement = cm.GetPreviousElementFor(XLWSContentManager.XLWSContents.RowBreaks); worksheetPart.Worksheet.InsertAfter(new RowBreaks(), previousElement); } var rowBreaks = worksheetPart.Worksheet.Elements<RowBreaks>().First(); var rowBreakCount = xlWorksheet.PageSetup.RowBreaks.Count; if (rowBreakCount > 0) { rowBreaks.Count = (UInt32)rowBreakCount; rowBreaks.ManualBreakCount = (UInt32)rowBreakCount; var lastRowNum = (UInt32)xlWorksheet.RangeAddress.LastAddress.RowNumber; foreach (var break1 in xlWorksheet.PageSetup.RowBreaks.Select(rb => new Break { Id = (UInt32)rb, Max = lastRowNum, ManualPageBreak = true })) rowBreaks.AppendChild(break1); cm.SetElement(XLWSContentManager.XLWSContents.RowBreaks, rowBreaks); } else { worksheetPart.Worksheet.RemoveAllChildren<RowBreaks>(); cm.SetElement(XLWSContentManager.XLWSContents.RowBreaks, null); } #endregion #region ColumnBreaks if (!worksheetPart.Worksheet.Elements<ColumnBreaks>().Any()) { var previousElement = cm.GetPreviousElementFor(XLWSContentManager.XLWSContents.ColumnBreaks); worksheetPart.Worksheet.InsertAfter(new ColumnBreaks(), previousElement); } var columnBreaks = worksheetPart.Worksheet.Elements<ColumnBreaks>().First(); var columnBreakCount = xlWorksheet.PageSetup.ColumnBreaks.Count; if (columnBreakCount > 0) { columnBreaks.Count = (UInt32)columnBreakCount; columnBreaks.ManualBreakCount = (UInt32)columnBreakCount; var maxColumnNumber = (UInt32)xlWorksheet.RangeAddress.LastAddress.ColumnNumber; foreach (var break1 in xlWorksheet.PageSetup.ColumnBreaks.Select(cb => new Break { Id = (UInt32)cb, Max = maxColumnNumber, ManualPageBreak = true })) columnBreaks.AppendChild(break1); cm.SetElement(XLWSContentManager.XLWSContents.ColumnBreaks, columnBreaks); } else { worksheetPart.Worksheet.RemoveAllChildren<ColumnBreaks>(); cm.SetElement(XLWSContentManager.XLWSContents.ColumnBreaks, null); } #endregion #region Drawings //worksheetPart.Worksheet.RemoveAllChildren<Drawing>(); //{ // OpenXmlElement previousElement = cm.GetPreviousElementFor(XLWSContentManager.XLWSContents.Drawing); // worksheetPart.Worksheet.InsertAfter(new Drawing() { Id = String.Format("rId{0}", 1) }, previousElement); //} //Drawing drawing = worksheetPart.Worksheet.Elements<Drawing>().First(); //cm.SetElement(XLWSContentManager.XLWSContents.Drawing, drawing); #endregion #region Tables worksheetPart.Worksheet.RemoveAllChildren<TableParts>(); { var previousElement = cm.GetPreviousElementFor(XLWSContentManager.XLWSContents.TableParts); worksheetPart.Worksheet.InsertAfter(new TableParts(), previousElement); } var tableParts = worksheetPart.Worksheet.Elements<TableParts>().First(); cm.SetElement(XLWSContentManager.XLWSContents.TableParts, tableParts); tableParts.Count = (UInt32)xlWorksheet.Tables.Count(); foreach ( var tablePart in from XLTable xlTable in xlWorksheet.Tables select new TablePart {Id = xlTable.RelId}) tableParts.AppendChild(tablePart); #endregion #region LegacyDrawing if (xlWorksheet.LegacyDrawingIsNew) { worksheetPart.Worksheet.RemoveAllChildren<LegacyDrawing>(); { if (!XLHelper.IsNullOrWhiteSpace(xlWorksheet.LegacyDrawingId)) { var previousElement = cm.GetPreviousElementFor(XLWSContentManager.XLWSContents.LegacyDrawing); worksheetPart.Worksheet.InsertAfter(new LegacyDrawing {Id = xlWorksheet.LegacyDrawingId}, previousElement); } } } #endregion #region LegacyDrawingHeaderFooter //LegacyDrawingHeaderFooter legacyHeaderFooter = worksheetPart.Worksheet.Elements<LegacyDrawingHeaderFooter>().FirstOrDefault(); //if (legacyHeaderFooter != null) //{ // worksheetPart.Worksheet.RemoveAllChildren<LegacyDrawingHeaderFooter>(); // { // var previousElement = cm.GetPreviousElementFor(XLWSContentManager.XLWSContents.LegacyDrawingHeaderFooter); // worksheetPart.Worksheet.InsertAfter(new LegacyDrawingHeaderFooter { Id = xlWorksheet.LegacyDrawingId }, // previousElement); // } //} #endregion }
public XLRows(XLWorksheet worksheet) { _worksheet = worksheet; style = new XLStyle(this, XLWorkbook.DefaultStyle); }