Skip to main content
You are viewing help content for pre-release software. This document and the features it describes are subject to change.
All docs
V26.2
  • Merge Workbooks and Extract Sheets

    • 8 minutes to read

    The Spreadsheet Document API allows you to combine sheets from multiple workbooks and to copy sheets from a workbook to a new workbook. You can merge workbooks into a new workbook, copy sheets from other workbooks to an existing workbook, or extract specified sheets to a new workbook. These operations copy worksheets and chart sheets and do not modify source workbooks.

    Merge Workbooks into a New Workbook

    Call the static Workbook.Merge(workbooks) method to create a workbook with copies of sheets from the specified workbooks. Copied sheets follow the order of workbooks in the workbooks array.

    The merged workbook does not contain document properties of source workbooks. Use the Workbook.DocumentProperties property to specify document properties of the merged workbook.

    The following code snippet merges a workbook with a cover sheet and a workbook from Document.xlsx into a new workbook and saves the merged workbook to a file:

    using System.IO;
    using DevExpress.Docs.Spreadsheet;
    
    Directory.CreateDirectory("output");
    
    // Create a workbook with a cover sheet.
    using Workbook cover = new Workbook();
    cover.Worksheets[0].Name = "Cover";
    cover.Worksheets[0].Cells["A1"].Value = "Annual Report";
    
    // Load a workbook from a file.
    using FileStream stream = File.OpenRead("Document.xlsx");
    using Workbook report = new Workbook(stream);
    
    // Merge the workbooks into a new workbook.
    using Workbook merged = Workbook.Merge(cover, report);
    
    // Calculate formulas in the merged workbook.
    merged.Calculate();
    
    using FileStream output = File.Create(Path.Combine("output", "Document.xlsx"));
    merged.Save(output);
    

    Append Sheets to an Existing Workbook

    Call the Workbook.Append(workbooks) method to copy sheets from other workbooks to the end of the current workbook. The current workbook keeps existing sheets, cell styles, table styles, workbook-scoped defined names, and document properties.

    If the API cannot copy a source workbook, the Append method throws an Exception and does not modify the current workbook.

    The following code snippet appends a workbook with Sheet1 and Report worksheets to a workbook with a Sheet1 worksheet and displays sheet names and the copied Report formula in the console:

    using System;
    using DevExpress.Docs.Spreadsheet;
    
    using Workbook target = new Workbook();
    target.Worksheets[0].Cells["A1"].Value = 10;
    
    // Create a source workbook with Sheet1 and Report worksheets.
    using Workbook source = new Workbook();
    source.Worksheets[0].Cells["A1"].Value = 100;
    Worksheet report = new Worksheet("Report");
    source.Worksheets.Add(report);
    report.Cells["A1"].Formula = "=Sheet1!A1*2";
    
    // Copy source sheets to the end of the target workbook.
    target.Append(source);
    target.Calculate();
    
    foreach (Sheet sheet in target.Sheets)
        Console.WriteLine(sheet.Name);
    
    Worksheet copiedReport = target.Worksheets[2];
    Console.WriteLine($"{copiedReport.Cells["A1"].Formula} = {copiedReport.Cells["A1"].Value}");
    

    Resolve Name Conflicts

    Merge and Append methods apply the following rules when they copy content from source workbooks to the target workbook:

    Content Result
    Sheet names If the target workbook contains a sheet with the same name (sheet names are case-insensitive), the API adds a number in parentheses to the copied sheet name (for example, Sheet1 (2)). If the new name exceeds 31 characters, the API shortens the original name.
    Formula references Formulas in copied sheets refer to copied sheets, including renamed sheets.
    Workbook-scoped defined names The API adds workbook-scoped names to the target workbook. If the target workbook contains a workbook-scoped name with the same name, the API keeps the target name. The source name becomes a worksheet-scoped name on each worksheet copied from the source workbook. Formulas in these worksheets use the source name definition.
    Worksheet-scoped defined names Copied worksheets keep worksheet-scoped names.
    Cell styles The API adds cell styles applied to copied cells to the target workbook. If the target workbook contains a cell style with the same name, copied cells maintain the source style formatting settings.
    Table styles The API adds custom table styles applied to copied tables to the target workbook. If the target workbook contains a table style with the same name, copied tables use the target style. The API does not duplicate predefined table styles.
    Tables If the target workbook contains a table with the same name, the API assigns a unique name to the copied table.

    Extract Sheets to a New Workbook

    Call the Workbook.Extract(sheetIndexes) method to copy specified sheets to a new workbook. Sheet indexes refer to the Workbook.Sheets collection. Copied sheets follow the order of indexes in the sheetIndexes array.

    The new workbook gets the theme, calculation options, culture, and other workbook settings from the source workbook. The new workbook does not get workbook protection and encryption settings. Copied worksheets maintain worksheet protection. Formulas that refer to copied sheets refer to the copies in the new workbook.

    The Extract(sheetIndexes) method copies sheets as follows:

    • Copied sheets keep the visibility of source sheets. The specified sheets must include at least one visible sheet.
    • References to sheets that are not copied become external references to the source workbook.
    • The new workbook does not get document properties of the source workbook.

    To extract each sheet to a separate workbook, call the Extract method for each sheet index.

    The following code snippet saves each sheet of a workbook to a separate XLSX file:

    using System.IO;
    using DevExpress.Docs.Spreadsheet;
    
    Directory.CreateDirectory("output");
    
    // Create a workbook with three worksheets.
    using Workbook workbook = new Workbook();
    workbook.Worksheets[0].Name = "January";
    workbook.Worksheets.Add(new Worksheet("February"));
    workbook.Worksheets.Add(new Worksheet("March"));
    for (int i = 0; i < workbook.Worksheets.Count; i++)
        workbook.Worksheets[i].Cells["A1"].Value = workbook.Worksheets[i].Name + " Sales";
    
    for (int i = 0; i < workbook.Sheets.Count; i++) {
        // Copy the sheet to a new workbook and save the new workbook to a file.
        string fileName = Path.Combine("output", workbook.Sheets[i].Name + ".xlsx");
        using Workbook part = workbook.Extract(i);
        using FileStream output = File.Create(fileName);
        part.Save(output);
    }
    

    Specify Extraction Options

    To customize sheet copying, pass a WorkbookExtractionOptions object to the Workbook.Extract(options, sheetIndexes) method. Use the following properties to specify extraction options:

    Property Description
    UnhideSheets Gets or sets whether copies of hidden and very hidden sheets are visible in the new workbook.
    ReplaceExternalReferencesWithValues Gets or sets whether to replace formulas with values if the formulas refer to sheets that are not extracted.
    PreserveDocumentProperties Gets or sets whether to copy document properties of the source workbook to the new workbook.

    If the ReplaceExternalReferencesWithValues property is true, the API replaces formulas that refer to sheets that are not extracted with current source cell values. The Extract method does not calculate the source workbook. To copy current formula results, call the Workbook.Calculate() method of the source workbook before the extraction.

    The following code snippet copies the Summary worksheet and document properties to a new workbook, replaces the formula that refers to the Data worksheet with the calculated value, and saves the new workbook to a file:

    using System.IO;
    using DevExpress.Docs.Spreadsheet;
    
    Directory.CreateDirectory("output");
    
    // Create a workbook with Data and Summary worksheets.
    using Workbook workbook = new Workbook();
    Worksheet data = workbook.Worksheets[0];
    data.Name = "Data";
    data.Cells["A1"].Value = 120;
    data.Cells["A2"].Value = 80;
    Worksheet summary = new Worksheet("Summary");
    workbook.Worksheets.Add(summary);
    summary.Cells["A1"].Formula = "=SUM(Data!A1:A2)";
    workbook.DocumentProperties.Title = "Sales Summary";
    
    // Calculate formulas before the extraction.
    workbook.Calculate();
    
    // Extract the Summary worksheet to a new workbook.
    WorkbookExtractionOptions options = new WorkbookExtractionOptions() {
        ReplaceExternalReferencesWithValues = true,
        PreserveDocumentProperties = true
    };
    using Workbook result = workbook.Extract(options, 1);
    
    using FileStream output = File.Create(Path.Combine("output", "Summary.xlsx"));
    result.Save(output);
    

    Calculate Formulas in the Resulting Workbook

    Merge and Append methods mark all formulas in the resulting workbook as not calculated, including formulas in existing sheets of the target workbook. The Extract method marks all formulas in the new workbook as not calculated. Formula cells have no results until you calculate formulas. Call the Workbook.Calculate() method of the resulting workbook before you read formula results.

    Refer to the following help topic for additional information: Calculate Formulas.