/// <summary> /// Inserts the append cloned worksheet part. /// </summary> /// <param name="action">The action.</param> /// <param name="targetWorkbookPart">The target workbook part.</param> /// <param name="sourceWorksheetPart">The source worksheet part.</param> /// <param name="sourceState">State of the source.</param> /// <param name="targetSheetName">Name of the target sheet.</param> /// <returns></returns> /// <exception cref="ArgumentNullException"> /// workbookPart /// or /// sourceWorksheetPart /// </exception> private static WorksheetPart InsertAppendClonedWorksheetPart(this InsertAppend action, WorkbookPart targetWorkbookPart, WorksheetPart sourceWorksheetPart, EnumValue <SheetStateValues> sourceState, string targetSheetName) { if (targetWorkbookPart == null) { throw new ArgumentNullException("workbookPart"); } if (sourceWorksheetPart == null) { throw new ArgumentNullException("sourceWorksheetPart"); } // take advantage of AddPart for deep cloning SpreadsheetDocument tempSheet = SpreadsheetDocument.Create(new MemoryStream(), SpreadsheetDocumentType.Workbook); WorkbookPart tempWorkbookPart = tempSheet.AddWorkbookPart(); WorksheetPart tempWorksheetPart = tempWorkbookPart.AddPart <WorksheetPart>(sourceWorksheetPart); // add cloned sheet and all associated parts to workbook WorksheetPart clonedSheet = targetWorkbookPart.AddPart <WorksheetPart>(tempWorksheetPart); // add new sheet to main workbook part Sheets sheets = targetWorkbookPart.Workbook.GetFirstChild <Sheets>(); var nextSheetId = sheets.GetNextSheetId(); targetSheetName = sheets.GetSafeSheetName(targetSheetName ?? "Sheet"); var newSheet = new DocumentFormat.OpenXml.Spreadsheet.Sheet { Id = targetWorkbookPart.GetIdOfPart(clonedSheet), // make sure the name is set to the provided name Name = targetSheetName, SheetId = nextSheetId, State = sourceState }; if (action == InsertAppend.Insert) { sheets.InsertAt(newSheet, 0); } else { sheets.Append(newSheet); } return(clonedSheet); }