Пример #1
0
        /// <summary>
        ///     Copies a sheet with a given sheet name and saves it with the clonedSheetName in the workbook
        /// </summary>
        /// <param name="docType">DocType to created for temp file in the method</param>
        /// <param name="workbookPart">Workbook which the worksheet to be copied and the copied worksheet to be saved</param>
        /// <param name="sheetName">Name of the worksheet to copy</param>
        /// <param name="clonedSheetName">New name of the copied sheet</param>
        private void copySheet(SpreadsheetDocumentType docType,
                               WorkbookPart workbookPart, string sheetName,
                               string clonedSheetName)
        {
            //Get the source sheet to be copied
            WorksheetPart sourceSheetPart = getWorksheetPart(workbookPart,
                                                             sheetName);
            //Take advantage of AddPart for deep cloning
            SpreadsheetDocument tempSheet =
                SpreadsheetDocument.Create(new MemoryStream(), docType);
            WorkbookPart tempWorkbookPart = tempSheet.AddWorkbookPart();
            WorksheetPart tempWorksheetPart =
                tempWorkbookPart.AddPart(sourceSheetPart);
            //Add cloned sheet and all associated parts to workbook
            WorksheetPart clonedSheet = workbookPart.AddPart(tempWorksheetPart);

            //Table definition parts are somewhat special and need unique ids...so let's make an id based on count
            int numTableDefParts =
                sourceSheetPart.GetPartsCountOfType<TableDefinitionPart>();
            _tableId = numTableDefParts;
            //Clean up table definition parts (tables need unique ids)
            if (numTableDefParts != 0) {
                fixupTableParts(clonedSheet);
            }
            //There should only be one sheet that has focus
            cleanView(clonedSheet);

            //Add new sheet to main workbook part
            var sheets = workbookPart.Workbook.GetFirstChild<Sheets>();
            var copiedSheet = new Sheet();
            copiedSheet.Name = clonedSheetName;
            copiedSheet.Id = workbookPart.GetIdOfPart(clonedSheet);
            copiedSheet.SheetId = (uint) sheets.ChildElements.Count + 1;
            sheets.Append(copiedSheet);
            //Save Changes
            workbookPart.Workbook.Save();
        }